标签:c语言
Given A,B,C, You should quickly calculate the result of A^B mod C. (1<=A,B,C<2^63).
There are multiply testcases. Each testcase, there is one line contains three integers A, B and C, separated by a single space.
For each testcase, output an integer, denotes the result of A^B mod C.
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; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:c语言
原文地址:http://blog.csdn.net/aaaaacmer/article/details/47281441