计蒜客-Exponial【快速幂+欧拉降幂】

Everybody loves big numbers (if you do not, you might want to stop reading at this point). There are many ways of constructing really big numbers known to humankind, for instance:

image.png

In this problem we look at their lesser-known love-child the exponial, which is an operation defined for all positive integers n as

 


image.png

 

For example, exponial(1) = 1 and exponial(5) = 5^{4^{3^{2^1}}}54321 ≈ 6.206 · 10^{183230}10183230 which is already pretty big. Note that exponentiation is right-associative: a^{b^c}abc = a^{(b^c)}a(bc).

Since the exponials are really big, they can be a bit unwieldy to work with. Therefore we would like you to write a program which computes exponial(n) mod m (the remainder of exponial(n) when dividing by m).

image.png

Input

The input consists of two integers n (1 ≤ n ≤ 10^9109) and m (1 ≤ m ≤ 10^9109).

Output

Output a single integer, the value of exponial(n) mod m. 

 

思路:

求a^b mod c的问题时,可以用快速幂,复杂度为log(n),可是如果指数太大的话需要用欧拉降幂。

欧拉降幂公式:

\left\{\begin{matrix} A^{B}mod (C)=A^{Bmod(phi(C))}modC& (B<phi(C)) \\ A^{B}mod (C)=A^{Bmod(phi(C))+phi(C)}modC& (B>=phi(C)) \end{matrix}\right.

(phi(C)为C的欧拉值)

 

我们发现当指数以递归的形式出现时,C也可以随之递归下去,且C的下降速度是非常快的,当C变为1时,根据2式,直接返回1即可。计算完指数,然后进行快速幂即可。

我们还可以发现1式只会出现在n<=4时,可以打个表。

 

代码:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll n,m;
ll biao[5]={0,1,2,9,(1<<18)};
ll mod_pow(ll x, ll n, ll mod)
{
    ll res = 1;
    while(n > 0)
    {
        if(n & 1) res = res * x % mod;
        x = x * x % mod;
        n >>= 1;
    }
    return res;
}
ll euler(ll n)
{
    ll res=n,a=n;
    for(ll 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;
}

ll dfs(ll n,ll mod)
{
    if(mod==1) return 1;
    if(n<=4)
    {
        if(biao[n]<mod) return biao[n];
        return biao[n]%mod+mod;
    }
    ll p=dfs(n-1,euler(mod));
    return mod_pow(n,p,mod)+mod;
}
int main()
{
    scanf("%lld%lld",&n,&m);
    ll p=dfs(n-1,euler(m));
    ll ans=mod_pow(n,p,m);
    printf("%lld\n",ans);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值