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.
Example 1:
Input: a = 2, b = [3]
Output: 8
Example 2:
Input: a = 2, b = [1,0]
Output: 1024
Example 3:
Input: a = 1, b = [4,3,3,8,5,2]
Output: 1
Constraints:
- 1 <= a <= 231 - 1
- 1 <= b.length <= 2000
- 0 <= b[i] <= 9
- b does not contain leading zeros.
此题的关键在于理解一个公式, a _ b % k = (a % k) _ (b % k) % k, 至于这个公式怎么推出来的, 我不知道, 我也是抄作业抄来的。
impl Solution {
fn pow(a: i32, b: i32) -> i32 {
let a = a % 1337;
let mut ans = 1;
for _ in 0..b {
ans *= a;
ans %= 1337;
}
ans
}
pub fn super_pow(a: i32, mut b: Vec<i32>) -> i32 {
if let Some(last_digit) = b.pop() {
if last_digit == 0 {
return Solution::pow(Solution::super_pow(a, b), 10);
}
b.push(0);
return (Solution::super_pow(a, b) % 1337) * (Solution::pow(a, last_digit) % 1337)
% 1337;
}
1
}
}