Fast Power
Original title Link: http://lintcode.com/en/problem/fast-power/#
Calculate the An % b where a, B and n is all 32bit integers.
Example
For 231% 3 = 2
For 1001000% 1000 = 0
Challenge
O (LOGN)
Tags Expand
Solution 1:
In fact, the problem should be suppose n > 0.
We use the multiplication rule of modulo operation: http://baike.baidu.com/view/4887065.htm
(A * b)% P = (a% p * b% p)% p (3)
A^n% B is decomposed into (a^ (N/2) * a^ (N/2) * (a))%b = ((a^ (N/2) * a^ (N/2))%b * (a)%b)%b = ((a^ (N/2)%b * a^ (N/2)%b)%b * (a)%b)%b
The implementation is as follows:
Note that 2 base case:n = 0 N = 1 are handled in particular. Because n = 1 o'clock, a POW (a, B, 1) will be decomposed, and this will be repeatedly called.
1 classSolution {2 /*3 * @param A, B, n:32bit integers4 * @return: An integer5 */6 /*7 * @param A, B, n:32bit integers8 * @return: An integer9 */Ten Public Static intFastpower (intAintBintN) { One //Write your code here A LongRET =Pow (A, b, n); - - return(int) ret; the } - - //Suppose n > 0 - Public Static LongPowintAintBintN) { + if(A = = 0) { - return0; + } A at //The base case. - if(n = = 0) { - return1%b; - } - - if(n = = 1) { in returnAb; - } to + LongRET = 0; - the //(A * b)% P = (a% p * b% p)% p (3) *ret = POW (A, B, N/2); $RET *=ret;Panax Notoginseng - //This step is to prevent overflow theRET%=b; + A if(n% 2 = = 1) { theRET *= POW (A, B, 1); + } - $ //perform the take-out Operation $RET = ret%b; - - returnret; the } -};View Code
Solution 2:
Or you can write the Pow (A, B, 1) directly as a% B. The following solution takes base case:n = 1 off.
1 //Solution 2:2 //Suppose n > 03 Public Static LongPowintAintBintN) {4 if(A = = 0) {5 return0;6 }7 8 //The base case.9 if(n = = 0) {Ten return1%b; One } A - LongRET = 0; - the //(A * b)% P = (a% p * b% p)% p (3) -ret = POW (A, B, N/2); -RET *=ret; - + //This step is to prevent overflow -RET%=b; + A if(n% 2 = = 1) { atRET *= (a%b); - } - - //perform the take-out Operation -RET = ret%b; - in returnret; -}View Code
GITHUB:
Https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/lintcode/math/FastPower.java
Lintcode:fast Power Problem Solving report