inzva / Algorithm-Program

A collection of editorials and tutorials about Algorithms and Data Structures

Home Page:https://inzva.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Integer overflow in fast exponentiation function

berkay-ozkan opened this issue · comments

On the 34th page of the 3rd bundle (math I), a fast exponentiation function is written as such:

long long fastExp(long long n, long long k){
    if(k == 0) return 1;
    if(k == 1) return n;
    
    long long temp = fastExp(n, k>>1);
    
    // If k is odd return n * temp * temp
    // If k is even return temp * temp
    // Take mod, since we can have a large number that overflows from long long
    if((k&1) == 1) return (n * temp * temp) % mod
    return (temp * temp) % mod;
}

An integer overflow may occur on line 10, as n is multiplied by temp twice in a row without any modulo operations in between.

I agree with @berkay-ozkan, the following part might lead to overflow in case $n * mod ^ 2 > 2^{62}$:

  • return (n * temp * temp) % mod

Better to have in this form:

  • return (((temp * temp) % mod) * n) % mod