您的位置:首页 > 其它

Math-372-Super Pow

2018-01-30 12:16 323 查看
Description:

Your task is to calculate abab 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


Best Solution:

public class Solution {
private static final int M = 1337;

public int normalPow(int a, int b) {
int result = 1;
while (b != 0) {
if (b % 2 != 0)
result = result * a % M;
a = a * a % M;
b /= 2;
}
return result;
}

public int superPow(int a, int[] b) {
a %= M;
int result = 1;
for (int i = b.length - 1; i >= 0; i--) {
result = result * normalPow(a, b[i]) % M;
a = normalPow(a, 10);
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: