LintCode-Fast Power

LiBlog發表於2014-12-25

Calculate the an % b where a, b and n are all 32bit integers.

Example

For 231 % 3 = 2

For 1001000 % 1000 = 0

Challenge

O(logn)

Solution:

 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         if (n==0) return 1%b;
 8 
 9         int res = fastPowerRecur(a,b,n);
10         return res;
11     }
12 
13     public int fastPowerRecur(int a, int b, int n){
14         if (n==1)
15             return a%b;
16     
17         long temp = fastPowerRecur(a,b,n/2);
18         temp = temp*temp%b;
19         int res = (n%2==0) ? (int) temp: (int)(temp*a%b);
20         return res;
21     }
22 };

 

相關文章