原题网址:https://leetcode.com/problems/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 % 1337 = n * 1337 + m,b % 1337 = p * 1337 + q,则a*b % 1337 = m * q % 1337
public class Solution {
private int[] mod;
private int mod(int a, int p) {
if (mod[p] > 0) return mod[p];
if (p == 0) {
mod[p] = a % 1337;
return mod[p];
}
int m = 1;
for(int i = 0; i < 10; i++) {
m *= mod(a, p - 1);
m %= 1337;
}
mod[p] = m;
return mod[p];
}
public int superPow(int a, int[] b) {
if (a % 191 == 0 && a % 7 == 0) return 0;
mod = new int[b.length];
int m = 1;
for(int i = 0; i < b.length; i++) {
for(int j = 1; j <= b[i]; j++) {
m *= mod(a, b.length - 1 - i);
m %= 1337;
}
}
return m;
}
}