problem 1752 a^b mod Caccept: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 is multiply testcases. Each testcase, there are 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 INPUT3 2 Output124 Source
Fzu Summer Training iv--number theory
Large number of processing. The data range reaches 2^63, so use unsigned long long.
But still want to explode, so uses the addition, for consumes the time the% operation, uses the subtraction substitution directly.
#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;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Fzu 1752 a^b MoD C