UVa 374 Big Mod
二分法求幂+取模
求BP mod M
根据分治的思想 divide & conquer:
if (P is even) BP = (BP/2)2;
else BP = (BP-1)*B;
将P转换成二进制后得到0-1序列,通过观察易知规律
为了容易理解,先考虑 P = 2n 的情况,此时BP = B2n;
即:
whlie (n--){
B *= B;
}
如:B=3,P = 4, 3*3 = 9, 9*9 = 81;
如果P = 111(2进制), BP = 34*32*31;
那对于P = 101呢? 中间的一位变成了零,BP = 34*31;(32不乘进去就行了),
于是算法为:
用变量t保存位权(我们这样称呼34、32、31这些权),x保存结果,初始化为1;
对P进行二进制转换,如果当前位是1,则用 t 乘x;
code
//12ms 2010-05-14 20:00:09
//Type: 二分求幂
#include <stdio.h>
#include <string.h>
int main()
{
int B, P, M;
while (scanf("%d%d%d", &B, &P, &M) != EOF) {
if (B == 0) { printf("0\n"); continue; }
if (P == 0) { printf("1\n"); continue; }
B %= M;
int t = B;
int x = 1;
while (P>0) {
if (P&1) x = (x*t)%M;
t = (t*t)%M;
P /= 2;
}
printf("%d\n", x);
}
return 0;
}