Calculate the a^n % b where a, b and n are all 32bit integers.
Example
For 2^31 % 3 = 2
For 100^1000 % 1000 = 0
分析:
利用公式:
(a * b) % p = (a % p * b % p) % p
a^n % b = (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
1 class Solution { 2 /* 3 * @param a, b, n: 32bit integers 4 * @return: An integer 5 */ 6 public int fastPower(int a, int b, int n) { 7 8 if (a == 0) return 0; 9 if (n == 0) return 1 % b; 10 if (n == 1 || a == 1) return a % b; 11 12 long temp = fastPower(a, b, n / 2); 13 temp = temp * temp; 14 temp = temp % b; 15 if (n % 2 == 1) { 16 temp = temp * (a % b); 17 return (int)(temp % b); 18 } else { 19 return (int)temp; 20 } 21 } 22 };