Exponial

Description

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:

  • Exponentiation: 422016=4242...422016 times422016=42⋅42⋅...⋅42⏟2016 times.
  • Factorials: 2016!=2016 ⋅ 2015 ⋅ ... ⋅ 2 ⋅ 1.

Illustration of exponial(3) (not to scale), Picture by C.M. de Talleyrand-Périgord via Wikimedia Commons

In this problem we look at their lesser-known love-child the exponial, which is an operation defined for all positive integers n as 
exponial(n)=n(n − 1)(n − 2)21
For example, exponial(1)=1 and exponial(5)=54321 ≈ 6.206 ⋅ 10183230 which is already pretty big. Note that exponentiation is right-associative: abc = 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 computesexponial(n) mod m (the remainder of exponial(n) when dividing by m).

Input

There will be several test cases. For the each case, the input consists of two integers n (1 ≤ n ≤ 109) and m (1 ≤ m ≤ 109).

Output

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

Sample Input

2 42
5 123456789
94 265

Sample Output

2
16317634
39

题解:题意很好理解;直接说题。这是利用欧拉函数降幂公式求的,标准模版(记得开 long long);看代码()

AC代码为:(我下面有一篇讲下欧拉函数降幂公式)


#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;


typedef long long LL;
LL N,M;


LL eular(LL m)
{
LL res=m,a=m;
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 Fast_mod(LL x,LL n,LL m)
{
LL res=1;
while(n>0)
{
if(n & 1) res=(res*x)%m;
x=(x*x)%m;
n/=2;
}
return res;
}


LL work(LL n,LL m)
{
LL ans;
if(m==1) return 0;
else if(n==1) return 1;
else if(n==2) return 2%m;
else if(n==3) return 9%m;
else if(n==4) return Fast_mod(4,9,m);
else
{
LL phi=eular(m);
LL z=work(n-1,phi);
ans=Fast_mod(n,phi+z,m);
}
return ans;
}


int main()
{
cin>>N>>M;
cout<<work(N,M)<<endl;
return 0;
}



posted @ 2018-04-06 14:43  StarHai  阅读(238)  评论(0编辑  收藏  举报