您的位置:首页 > 其它

LeetCode 372 Super Pow

2016-07-11 10:13 435 查看
Your task is to calculate ab mod 1337 where a is a positive integer and b is
an extremely large positive integer given in the form of an array.

Example1:
a = 2
b = [3]

Result: 8


Example2:
a = 2
b = [1,0]

Result: 1024


思路

由于直接ab%1337会溢出,b本身也会溢出,它是一个超大数,所以ab%1337我们变换成
 (a%1337)*(a%1337) %1337*(a%1337)%1337……这样处理。具体看代码吧。一目了然。

算法需要利用的恒等式  (a*b)%c
= (a%c)*(b%c)%c,证明如下

 设a/c=m,则mc+a%c =a;设b/c=n,则nc+b%c =b;于是
  (a*b)%c 
= { (mc+a%c)*(nc+b%c ) }%c 
= {mcnc+(nc)*(a%c)+(mc)*(b%c)+(a%c)*(b%c)} % c (其中 mcnc+(nc)*(a%c)+(mc)*(b%c)可以整除c)
= (a%c)*(b%c)%c


代码实现如下:

public int superPow(int a, int[] b) {
int res = 1;
for (int i = 0; i < b.length; i++) {
res = pow(res, 10) * pow(a, b[i]) % 1337;
}
return res;
}

public int pow(int a, int b) {
if (b == 0) return 1;
if (b == 1) return a % 1337;
return pow(a % 1337, b / 2) * pow(a % 1337, b - b / 2) % 1337;
}


参考:discuss
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode