Integer overflow in fast exponentiation function
berkay-ozkan opened this issue · comments
Berkay Özkan commented
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.
Kerim Kochekov commented
I agree with @berkay-ozkan, the following part might lead to overflow in case
return (n * temp * temp) % mod
Better to have in this form:
return (((temp * temp) % mod) * n) % mod