求$$2^{2^{2^{2^{…}}}} mod n$$的值,其中n有1e7。
老实说这题挺有趣的,关键是怎么化掉指数,由于是取模意义下的无限个指数,所以使用欧拉定理一定是可以把指数变为不大于$\varphi(n)$的,但是我们连上一层指数的值都不知道,怎么化阿...
考虑同余定理,把n变为$n=2^k·s$的形式,然后$2^k$先提取出来,这样每向一层模数会减少,最后到1这样最后一层可以得到0的值了,回溯时计算完一层的指数时再把$2^k$乘回去就好了
/** @Date : 2017-09-11 21:22:36
* @FileName: bzoj 3884 欧拉降幂.cpp
* @Platform: Windows
* @Author : Lweleth (SoungEarlf@gmail.com)
* @Link : https://github.com/
* @Version : $Id$
*/
#include <bits/stdc++.h>
#define LL long long
#define PII pair<int ,int>
#define MP(x, y) make_pair((x),(y))
#define fi first
#define se second
#define PB(x) push_back((x))
#define MMG(x) memset((x), -1,sizeof(x))
#define MMF(x) memset((x),0,sizeof(x))
#define MMI(x) memset((x), INF, sizeof(x))
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 1e7+20;
const double eps = 1e-8;
LL fpow(LL a, LL n, LL mod)
{
LL res = 1;
while(n)
{
if(n & 1)
res = (res * a % mod + mod) %mod;
a = (a * a % mod + mod ) % mod;
n >>= 1;
}
return res;
}
int pri[N];
int phi[N];
int c = 0;
void prime()
{
MMF(phi);
phi[1] = 1;
for(int i = 2; i < N; i++)
{
if(!phi[i])
pri[c++] = i, phi[i] = i - 1;
for(int j = 0; j < c && i * pri[j] < N; j++)
{
phi[i * pri[j]] = 1;
if(i % pri[j] == 0)//是倍数i=kp, phi(kpp)=kpp*[phi(kp)/kp]=p*phi(kp)
{
phi[i * pri[j]] = phi[i] * pri[j];
break;
}
else //积性函数性质 (i, p) = 1, phi(ip)=phi(i)*phi(p)
phi[i * pri[j]] = phi[i] * (pri[j] - 1);
}
}
}
int get_phi(int x)
{
int phi = x;
for(int i = 2; i * i <= x; i++)
{
if(x % i == 0)
{
while(x % i==0)
x /= i;
phi = phi / i * (i - 1);
}
}
if(x > 2)
phi = phi / x * (x - 1);
return phi;
}
int dfs(int p)
{
if(p == 1)
return 0;
int k = 0;
while(p % 2 == 0)
p>>=1, k++;
int s = p;
int phis = get_phi(s);/*phi[s];*/
int nxe = dfs(phis);//模数向上递归
nxe = (nxe - k % phis + phis) % phis;//欧拉降幂
nxe = fpow(2, nxe, s) % s;
return nxe << k;
}
int main()
{
int T;
//prime();
cin >> T;
while(T--)
{
int mod;
scanf("%d", &mod);
printf("%d\n", dfs(mod));
}
return 0;
}