Super A^B mod C - FZU - 1759 - 降幂公式

本文介绍了一种高效计算大数幂取模的方法,利用欧拉函数和快速幂算法解决大数幂运算问题,并提供了一个完整的AC代码实现。
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;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值