这个算法的思想我是从一本书上看到的,对合法的输入能很快的计算出结果来,其思想是利用
数学公式: (a * b ) mod c = (( a mod c) * b) mod c;
首先把 b 转化成二进制如: b0 b1 b2 b3..... b31 即 b = b0*231 + b1*230+......+ b31;
也就是把 ab = a ^ (b0*231 + b1*230+......+ b31) = [a(b0*2^31)] * [a(b1*2^30)] *..... * [ab31*2^0];
所以如果b的化成二进制的某位为0时,可以直接用这样算 resualt = (resualt * resualt)%c;
若为1 则为 resualt = ( resualt * a) % c;
例如:35 mod 4 ; 5转化成二进制为101,即35 = 3(2^2) * 3(2^0) = 34 * 31
所以35 mod 4 = 34 * 3 mod 4 = ((34)mod 4 * 3)mod 4;
31 mod 4 = 3, 32 mod 4 = (31 * 3 1) mod 4 ; 34 mod 4 = (32 *32)mod 4;
![](https://i-blog.csdnimg.cn/blog_migrate/a41954a27d6ad96fa2c2cf816e677448.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/1327ab569c1ae82736693a50b8e33378.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)