Super A^B mod C
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
题意:求大数的幂函数。
题解:解题需要用到欧拉函数和降幂公式,降幂公式为
。
AC代码:
#include<cstdio>
#include<cstring>
using namespace std;
long long phi(long long x)//求欧拉函数。
{
int res = x,a = x;
for(int i=2;i*i<=a;i++)
{
if(a%i==0)
{
res = res/i*(i-1);
while(a%i==0)a/=i;
}
}
if(a>1)res =res/a*(a-1);
return res;
}
long long qq(long long a,int b,long long c)//快速幂。
{
long long ans=1;
while(b)
{
if(b&1)ans=ans*a%c;
a=a*a%c;
b=b>>1;
}
return ans;
}
long long a,c;
char s[1000010];
int main()
{
while(scanf("%I64d %s %I64d",&a,s,&c)!=EOF)
{
long long phic = phi(c);
a%=c;
int length = strlen(s);
long long res = 0;
int i;
for(i=0;i<length;i++)
{
res = res*10+s[i]-'0';
if(res>phic)break;
}
if(i==length)//降幂公式需要用在res>phic的情况下,否则直接求快速幂即可。
{
printf("%I64d\n",qq(a,res,c));
}
else
{
res=0;
for(i=0;i<length;i++)
{
res = res*10+s[i]-'0';
res=res%phic;
}
printf("%I64d\n",qq(a,res+phic,c));
}
}
return 0;
}
本文介绍了一种高效计算大数幂取模的方法,利用欧拉函数和快速幂算法解决大数幂运算问题,并提供了一个完整的AC代码实现。
358

被折叠的 条评论
为什么被折叠?



