372. Super Pow(超级次方)
题目描述:
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
说明:理解题意,即计算 (a^b)%1377
的值(其中,a
是一个整数,b
是一个由数组表示的非常大的正整数)
要求:输入正整数 a
,数组 b
返回 (a^b)%1337
的值
题解:
快速幂取模的变形,分析 f = (x^y)%k
对于 y = [t1,t2,t3,t4]
则 f = (x^(t1*1000+t2*100+t3*10+t4))
例如 y = [2,3,4,5] 则 f = (x^2345)%1337
即 f = ((x^1000)^2*(x^300)*(x^40)*(x^5))%k
= ((x^1000)^2*(x^100)^3*(x^10)^4*(x^1)^5)%k
利用数学模运算基本公式 :·(a*b)%p = (a%p*b%p)%p·
则,实现如下
Code:
package codimgTest1;
public class Mian {
public static void main(String[] args){
int[]y = new int[]{1,0};
System.out.print( superPow(2,y));
}
public static int superPow(int x,int[] y){
long ans = 1;
long a = x;
for(int i=y.length-1;i>=0;i--){
ans = ans*newPow(a,y[i]%1377);
a = newPow(a,10);
}
return (int)ans;
}
private static int newPow(long x, int y) {
long ans = 1;
long a = x;
while (y > 0) {
if ((y & 1) > 0) {
ans = ans * a % 1377;
}
y >>= 1;
a = a * a % 1377;
}
return (int) ans;
}
}