上帝与集合的正确用法

题目:

求2^2^2^……(无限个2)%p。

题解:
温习欧拉公式:

a,p互质,有a^phi[ p ] ≡ 1( mod p )

怎么用?

假设k = 2^2^2^……

那么求k%p

就是2^k%p(无穷特性)

然后等于2^(k%phi[ p ]+phi[ p ])%p

我们的问题变成求解k%phi[ p ]了。

最后当phi[ p ]==1时就可以直接返回0了。

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define T 1050
#define ll long long
int t;
int get_phi(int x)
{
    int ret = 1;
    for(int j=2;j*j<=x;j++)
    {
        if(x%j==0)
        {
            ret*=(j-1);
            x/=j;
            while(x%j==0)x/=j,ret*=j;
        }
    }
    if(x!=1)ret*=(x-1);
    return ret;
}
int p;
ll fast(ll x,ll y,int mod)
{
    ll ret = 1ll;
    while(y)
    {
        if(y&1)ret=ret*x%mod;
        x=x*x%mod;
        y>>=1;
    }
    return ret%mod;
}
ll f(int u)
{
    if(u==1)return 0;
    int phi = get_phi(u);
    return fast(2,f(phi)+phi,u);
}
int main()
{
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&p);
        printf("%lld\n",f(p));
    }
    return 0;
}

 

posted @ 2018-11-06 16:02  LiGuanlin  阅读(363)  评论(0编辑  收藏  举报