欧拉降幂

欧拉降幂公式:

 

对于a^b mod c当b达到10^6时,就无法使用快速幂,需利用欧拉降幂公式

 

求解2^987654321%1000000的值

这么大的幂方,是快速幂算法无法求解的,这时我们将使用欧拉降幂算法,它的特点就是能够降低幂方的值且不影响最终结果

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
typedef long long LL;
const int MAX=1000100;
LL qsm(LL a,LL b,LL mod)          //(a^b)%mod
{
    LL res=1;
    while(b>0)
    {
        if(b&1)
            res=(res%mod*a%mod)%mod;
        b>>=1;
        a=(a%mod*a%mod)%mod;
    }
    return res;
}

LL Euler(LL n)
{
    LL ans=1;
	for(int i=2;i*i<=n;i++)
    {
		if(n%i==0)
		{
			n/=i;
			ans*=(i-1);
			while(n%i==0)
			{
				n/=i;
				ans*=i;
			}
		}
	}
	if(n>1)
	  ans*=(n-1);
	return ans ;
}

//降幂函数
LL eulerDropPow(LL a,char b[],LL c)
{
    LL eulerNumbers=Euler(c);
    //存储降了之后的幂
    LL descendingPower=0;
    for(LL i=0,len=strlen(b);i<len;++i)
    {
        descendingPower=(descendingPower*10+b[i]-'0')%eulerNumbers;
    }
    descendingPower += eulerNumbers;
    return qsm(a,descendingPower,c);
}
int main() 
{
    LL a,c;
    char b[MAX];
    while(~scanf("%LLd%s%LLd",&a,b,&c))  //a的b次方对c取模
    {
        printf("%lld\n",eulerDropPow(a,b,c));
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值