LintCode Fast Power

Calculate the an % b where a, b and n are all 32bit integers.
Have you met this question in a real interview? Yes
Example
For 231 % 3 = 2
For 1001000 % 1000 = 0
Challenge
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
        int res = 1;
        long part = a;
        while (n) {
            if (n & 0x1) {
                res = res * part % b;
            }
            part = part * part % b; 
            n /= 2;
        }
        
        return res % b;
    }
};

posted @ 2015-09-14 00:37  卖程序的小歪  阅读(133)  评论(0编辑  收藏  举报