LintCode 快速幂

来源:互联网 发布:我国银行员工待遇数据 编辑:程序博客网 时间:2024/06/01 16:21

LintCode 快速幂

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

样例
例如
231 % 3 = 2

例如 1001000 % 1000 = 0

Solution:
显然不能先计算an之后再取余。因为,an会溢出。
因此,需要利用取模运算的乘法法则:

(a * b) % p = (a % p * b % p) % p

则有
an%p = (a1/2%p)×(a1/2%p)%p = ....
注意:
1. n = 0 和 n = 1的情况
2. n为奇数时

Talk is cheap, show me the code!

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;        else if (n < 0)            return -1;        long product = fastPower(a, b, n/2);        product = (product*product) % b;        if (n % 2 == 1)             product = (product * (a%b))%b; //equal: product = (product * a)%b;        return (int)(product);    }};

Reference:
Lintcode: Fast Power 解题报告 - Yu’s Garden - 博客园

0 0
原创粉丝点击