Problem 1752 A^B mod C
Accept: 840 Submit: 3625
Time Limit: 1000 mSec Memory Limit : 32768 KB
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
Source
FZU 2009 Summer Training IV--Number Theory
大数处理。数据范围达到2^63,所以要用unsigned long long 。
但还是要爆,所以采用加法,对于耗时间的%运算,直接利用减法替代。
#include<stdio.h>
#include<string.h>
#include<math.h>
#define LL unsigned __int64
LL quickmod(LL a,LL b,LL c)
{
LL ans=0;
a=a%c;
while(b)
{
if(b&1)ans+=a;
if(ans>=c)ans-=c;
a=a+a;
if(a>=c)a=a-c;
b=b/2;
}
return ans;
}
int main()
{
LL a,b,c,i,j,ans;
while(scanf("%I64u%I64u%I64u",&a,&b,&c)!=EOF)
{
ans=1;
a=a%c;
while(b)
{
if(b%2)ans=quickmod(ans,a,c);
a=quickmod(a,a,c);
b=b/2;
}
printf("%I64u\n",ans);
}
return 0;
}