【LEETCODE】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)%c=(a%c)*(b%c)
和 把 a^b 转化成 (a ^ (b/2))^2
不过要注意b 是奇数的情况,就是这时就要写成 b/2 和 b - b/2。
class Solution {
public:
int superPow(int a, vector<int>& b) {
a = a % 1337;
long long res = 1;
for (int i = 0; i < b.size(); i++) {
res = (pow(res, 10) % 1337) * (pow(a, b[i]) % 1337) % 1337;
}
return res;
}
int pow(int a, int n) {
if (n == 0) return 1;
if (n == 1) return a % 1337;
else return pow(a, n / 2) * pow(a, n - n / 2) % 1337;
}
};