快速幂—LintCode

来源:互联网 发布:js获取classname值 编辑:程序博客网 时间:2024/06/06 03:42

描述:
计算a^n % b,其中a,b和n都是32位的整数。

样例:
例如 2^31 % 3 = 2

例如 100^1000 % 1000 = 0

思路:

二分求幂。

ac代码:

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