accept:822 submit:3560
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 Sample Output
124
This problem because the data is relatively large, directly with the fast power template will be super unsigned long long range, so the same idea to calculate a*b/%c. Can be seen as a template. Enter with%llu or%i64u.
#include <stdio.h> #include <string.h> #define LL unsigned __int64ll mul (ll a,ll b,ll c) //With the idea of a fast power to seek a*b% C Prevent cross-border { 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;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Fzu 1650 1752 a^b MoD C