Description
Input
Output
Sample Input
2 3
12 6
6789 10000
0 0
Sample Output
8
984
1
-----------------------------------------------------我是分割线^_^--------------------------------------------------------------------
要特别注意一个结论:a*b%c = a%c * b%c.(也可以等于(a%c * b%c)%c,因为可能影响到结果)
这是一个快速幂取模的模板,除此之外还有快速乘取模,之后有一个题会说到
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
using namespace std;
int main()
{
//freopen("input.txt", "r", stdin);
int a, b;
while (scanf("%d%d", &a, &b), a || b) {
int ans = 1;
a %= 1000;
while (b > 0) {//快速幂取模
if (b % 2 == 1) {
ans = (ans * a) % 1000;//如果幂的次数是奇数,就优先一步乘入结果,让幂的次数变偶数
}
b>>=1;
a = (a * a) % 1000;//例如让2的四次方变成4的二次方,从而减少运算次数
}
printf("%d\n", ans);
}
return 0;
}
原文:http://www.cnblogs.com/steamedbun/p/5727617.html