LintCode-快速幂

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

样例

例如 231 % 3 = 2

例如 1001000 % 1000 = 0

挑战

O(logn)

分析:既然复杂度有要求,那么肯定是类似二分啦。

代码:

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(n==0)
            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;
    }
};


你可能感兴趣的:(面试,lintcode)