题目:http://acm.fzu.edu.cn/problem.php?pid=1752
Problem Description
Given A,B,C, You should quickly calculate the result of A^B mod C. (1<=A,B,C<2^63).
Input
There are multiply testcases. Each testcase, there is one line contains three integers A, B and C, separated by a single space.
Output
For each testcase, output an integer, denotes the result of A^B mod C.
Sample Input
3 2 42 10 1000
Sample Output
124
分析:
这题时间要求高,所以multi_mod和quick_mod一起使用,同时,不要使用%运算,那样很耗时间。
#include <iostream>
#include<cstdio>
using namespace std;
typedef long long LL;
LL multi_mod(LL a,LL b,LL c){
LL ans=0;
while(b){
if(b&1)ans=ans+a;
if(ans>=c)ans-=c;
a=a+a;
if(a>=c)a-=c;
b>>=1;
}
return ans;
}
int main()
{
//freopen("cin.txt","r",stdin);
LL a,b,c;
while(~scanf("%I64d%I64d%I64d",&a,&b,&c)){
LL ans=1;
a=a%c;
while(b){
if(b&1)ans=multi_mod(ans,a,c);
a=multi_mod(a,a,c);
b>>=1;
}
printf("%I64d\n",ans);
}
return 0;
}