快速幂

快速幂

快速幂

1 题目

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

2 方法

(ab)%c = (a%c * b%c)%c

3 挑战

O(log(n))

4 思路

采用二分法,每个幂次分为两半。

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

        return (fastPower(a, b, n / 2) * fastPower(a, b, (n + 1) / 2)) % b;
    }
};

很容易就想到了,但是,运行时间不是log(n)的。因为,本来每计算一次都会减为原来的一半,但是,我们这里,每次运行了两次,那最终就是n次了。 所以,需要把每次的结果记录下来,就不需要运行两次了。这样,如果是奇数的话,还需要用之前的偶数次再乘以一次。

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

        long product = fastPower(a, b, n / 2);
        product = product * product % b;

        if (n % 2 == 1) {
            product = (product * (a % b)) % b;
        }

        return (int)product;
    }
};

Date: 2016-12-25 14:15

Created: 2016-12-31 周六 10:22

Validate

原文地址:https://www.cnblogs.com/yangwen0228/p/6220419.html