LintCode-140.快速幂

快速幂

计算an % b,其中a,b和n都是32位的整数。

样例

  • 例如 231 % 3 = 2
  • 例如 1001000 % 1000 = 0

挑战

O(logn)

标签

分治法

code

class Solution {
public:
/*
* @param a, b, n: 32bit integers
* @return: An integer
/
int fastPower(int a, int b, int n) {
// write your code here
if(n0)
return 1%b;
if(n
1)
return a%b;
long long temp = fastPower(a,b,n/2);
if(n&1)
return ((temp
temp)%b)a%b;
else
return temp
temp%b;
}
};

posted @ 2017-05-04 14:20  LiBaoquan  阅读(414)  评论(0)    收藏  举报