题目:http://acm.fzu.edu.cn/problem.php?pid=1752
Problem 1752 A^B mod C
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 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
鉴于数据范围,用二分求A*B时要能得到A+A,当A=2^63时,A+A的大小就要用unsigned long long 存储。
#include<stdio.h>
#include<iostream>
using namespace std;
typedef unsigned long long LL;
LL a,b,c,ans;
inline LL mul_mod(LL x)
{
LL res=0,y=a;
while(x)
{
if(x&1)
{
res+=y;
while(res>=c)res-=c;
}
y<<=1;
x>>=1;
while(y>=c)y-=c;
}
return res;
}
int main()
{
while(scanf("%llu%llu%llu",&a,&b,&c)!=EOF)
{
ans=1;
a%=c;
while(b)
{
if(b&1)
ans=mul_mod(ans);
a=mul_mod(a);
b>>=1;
}
printf("%llu\n",ans);
}
return 0;
}
题目: http://acm.fzu.edu.cn/problem.php?pid=1759
【关于 A^x = A^(x % Phi(C) + Phi(C)) (mod C) 的若干证明】【指数循环节】
Problem 1759 Super A^B mod C
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,C<=1000000000,1<=B<=10^1000000).
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<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
typedef long long LL;
LL a,b,c,ans;
char str[1000009];
LL euler(LL x)
{
LL i,res=x;
if(x%2==0)
{
res=res-res/2;
while(x%2==0)x/=2;
}
for(i=3;i*i<=x;i+=2)
{
if(x%i==0)
res=res-res/i;
while(x%i==0)x/=i;
}
if(x>1)res=res-res/x;
return res;
}
int main()
{
while(scanf("%lld%s%lld",&a,str,&c)!=EOF)
{
LL phi=euler(c);
LL i;
LL len=strlen(str);
b=0;
if(len>=10)
{
for(i=0;str[i];i++)
b=(b*10+(str[i]-'0'))%phi;
b+=phi;
}
else //判断b>phi
{
for(i=0;str[i];i++)
b=b*10+(str[i]-'0');
if(b>phi)b=b%phi+phi;
}
ans=1;
a%=c;
while(b)
{
if(b&1)
ans=ans*a%c;
a=a*a%c;
b>>=1;
}
printf("%lld\n",ans);
}
return 0;
}