标签:
Calculate the an % b where a, b and n are all 32bit integers.
For 231 % 3 = 2
For 1001000 % 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 };
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5697753.html