问题描述
Your task is to calculate \(a^{b}\) mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.
Example1:
|
|
Example2:
|
|
思路
解法一:
最初的想法是利用 快速幂 的思想,由于指数特别大,所以在index >> 1
这一步需要自己写一个大数的除2方法来代替。
大数除2代码如下:
|
|
快速幂大致如下:
index是转化为string的大数指数。
|
|
提交可以AC,然而时间是1400ms,有点爆炸。主要问题应该是在大指数除法的时候,时间开销太大。
解法二:
充分利用了数学上求余的性质:
$$
a^{b} mod m = (a mod m)^{b} mod m
$$
还有例如:
$$
a^{k} mod m = (a mod m)^{k-1} \times (a mod m)^1 mod m
$$
利用以上性质,我们可以预先算出\(a^{0} 至 a^{9}\) 求余1337的余数,这可以大大加快后续的过程。
AC,时间只有12ms!!!
Code
解法一的代码在上面。
解法二:
|
|