F - A^B mod C
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 4
2 10 1000
Sample Output
1
24
#include<iostream>
using namespace std;
//ACM高精度模板综合偶然发现的,收藏一下。https://blog.csdn.net/u013615904/article/details/43373601
//思路参考博客https://blog.csdn.net/aaaaacmer/article/details/47281441
/*
乘 函数f的含义为计算a*b%c
*/
unsigned long long f(unsigned long long a,
unsigned long long b,
unsigned long long c)
{
//快速幂中间的乘法会炸,需要优化,用加法取代乘,用减法取代mod。
/* while(b>0)
{
if(b&1)
ans = (ans%c)*(a%c)%c;
a = (a%c)*(a%c)%c;
b>>=1;
}
*/
unsigned long long ans = 0;
while(b)
{
if(b&1)
ans+=a;
if(ans>=c)
ans-=c;
a=a+a;
if(a>=c)
a-=c;
b>>=1;
}
return ans;
}
int main()
{
unsigned long long a,b,c;
unsigned long long ans = 1;
while(cin>>a>>b>>c)
{
ans = 1;
// f();
a = a%c;
//快速幂
while(b)
{
if(b&1)
ans = f(ans,a,c);//计算ans*a%c
a=f(a,a,c);//计算a*a%c
b>>=1;
}
cout<<ans<<endl;
}
return 0;
}