题目:
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
思路:
不知道出题人为什么会想出来1337这么奇怪的数字?好像1337也不是素数。
这里需要用到两个关键的数学公式:
1) a^b % c = (a % c)^b % c;
2) ab % c = (a % c) * (b % c) % c。
其中1)可以让我们尽可能地缩减a的值,2)可以让我们递归地缩减b的值。当然为了防止溢出,我们需要自己实现一个计算(a^k % c)的函数。
代码:
class Solution {
public:
int superPow(int a, vector<int>& b) {
if(b.empty()) {
return 1;
}
a = a % 1337; // a^b % c = (a % c)^b % c
int last = b.back();
b.pop_back();
return (superPow(superPow(a, b), 10) * superPow(a, last)) % 1337; // a^(10b + c) = a^(10b) * a^c = (a^b)^10 * a^c
}
private:
int superPow(int a, int k) {
if(k == 0) {
return 1;
}
int ans = 1;
for(int i = 1; i <= k; ++i) { // ab % c = (a % c) * (b % c) % c
ans = (ans * a) % 1337;
}
return ans;
}
};