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

分析

使用递归来简化操作。

代码

public class Solution {

    /*
     * @param a: A 32bit integer
     * @param b: A 32bit integer
     * @param n: A 32bit integer
     * @return: An integer
     */
    public int fastPower(int a, int b, int n) {
        // write your code here
        if (n == 0) {
            return 1 % b;
        }
        a %= b;
        long res = fastPower(a, b, n / 2);
        res %= b;
        res *= res;
        res %= b;
        if (n % 2 != 0) {
            res *= a;
            res %= b;
        }
        return (int)res;
    }
}

你可能感兴趣的:(Fast Power(快速幂))