Given A,B,C, You should quickly calculate the result of A^B mod C. (1<=A,C<=1000000000,1<=B<=10^1000000).
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.
3 2 4 2 10 1000
1 24
题意:快速幂(其中幂指数特别大,long long也装不下,需要用字符串输入)
解法:
那个是欧拉函数
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
typedef long long ll;
using namespace std;
ll quckpow(ll m,ll n,ll k)
{
ll b=1;
while(n>0)
{
if(n&1)b=(b*m)%k;
n=n>>1;
m=(m*m)%k;
}return b;
}
ll phi(ll n)
{
ll i,rea=n;
for(i=2;i*i<=n;i++)
{
if(n%i==0)
{
rea=rea-rea/i;
while(n%i==0)n/=i;
}
}
if(n>1)
rea=rea-rea/n;
return rea;
}
char b[1000050];
int main()
{
ll a,c,ans;
while(scanf("%I64d%s%I64d",&a,b,&c)!=-1)
{
int len=strlen(b);
ll ph,t;
ph=phi(c);
if(len<=20)
{
sscanf(b, "%I64d", &t);
if(t>=ph)
t=t%ph+ph;
ans=quckpow(a,t,c);
}
else
{
t=0;
for(int i=0;i<len;i++)
{
t=t*10+b[i]-'0';
if(t>ph)
t=t%ph;
}ans=quckpow(a,t,c);
}
printf("%I64d\n",ans);
}
return 0;
}