Problem DescriptionGiven A,B,C, You should quickly calculate the result of A^B mod C. (1<=A,B,C<2^63).
InputThere are multiply testcases. Each testcase, there is one line contains three integers A, B and C, separated by a single space.
OutputFor each testcase, output an integer, denotes the result of A^B mod C.
Sample Input
Sample Output124
这题因为数据比较大,直接用快速幂模板会超unsigned long long 范围,所以用同样的思想计算a*b/%c.可以看做模板。输入用%llu 或%I64u.
#include<stdio.h>
#include<string.h>
#define ll unsigned __int64
ll mul(ll a,ll b,ll c) //用快速幂的思想求a*b%c防止越界
{
ll ret=0,tmp=a%c;
while(b)
{
if(b&1)
if((ret+=tmp)>=c)
ret-=c;
if((tmp<<=1)>=c)
tmp-=c;
b>>=1;
}
return ret;
}
ll f(ll a,ll b,ll c)
{
ll ans=1;
a=a%c;
while(b>0){
if(b%2==1){
ans=mul(ans,a,c);
}
b=b/2;
a=mul(a,a,c);
}
return ans;
}
int main()
{
ll n,m,i,j,a,b,c;
while(scanf("%I64u%I64u%I64u",&a,&b,&c)!=EOF)
{
printf("%I64u\n",f(a,b,c));
}
return 0;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/kirito_acmer/article/details/47258529