Take advantage of property of modular arithmetic
(x × y) modulo b == ((x modulo b) × (y modulo b)) modulo b
By using above multiplication rule
(a^n) modulo b
= (a × a × a × a ... × a) modulo b
= ((a modulo b) × (a modulo b) × (a modulo b) ... × (a modulo b)) modulo b
Calculate the result by divide and conquer approach. The recurrence relation will be:
f(x, n) = 0 if n == 0
f(x, n) = (f(x, n / 2))^2 if n is even
f(x, n) = (f(x, n / 2))^2 * x if n is odd
Here is the C++ implementation:
int powerUtil(int base, int exp, int mod) {
if(exp == 0) return 1;
int ret = powerUtil(base, exp / 2, mod) % mod;
ret = 1LL * ret * ret % mod;
if(exp & 1) {
ret = 1LL * ret * base % mod;
}
return ret;
}
double power(int base, int exp, int mod) {
if(exp < 0) {
if(base == 0) return DBL_MAX; // undefined
return 1 / (double) powerUtil(base, -exp, mod);
}
return powerUtil(base, exp, mod);
}
Time complexity is O(logn)
.
Here is my original answer. Hope it helps!