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:
In this problem we look at their lesser-known love-child the exponial, which is an operation defined for all positive integers n as
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).
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),可是如果指数太大的话需要用欧拉降幂。
欧拉降幂公式:
(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;
}