[数学][欧拉降幂定理]Exponial

Posted lllxq

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[数学][欧拉降幂定理]Exponial相关的知识,希望对你有一定的参考价值。

题目描述

技术分享图片
Illustration of exponial(3) (not to scale), Picture by C.M. de Talleyrand-Périgord via Wikimedia Commons 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 de?ned for all positive integers n as
技术分享图片
For example, exponial(1) = 1 and  技术分享图片which is already pretty big. Note that exponentiation is right-associative:  技术分享图片.
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).

 

输入

The input consists of two integers n (1 ≤ n ≤ 109 ) and m (1 ≤ m ≤ 109 ).

 

输出

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

 

样例输入

2 42

 

样例输出

2
欧拉降幂定理:当b>phi(p)时,有a^b%p=a^(b%phi(p)+phi(p))%p
思路:当n>=6时,欧拉降幂定理一定适用,因为f(5)>1e9,也就是一定有欧拉降幂定理的b>phi(p)这个条件,所以f(n)%p=n^f(n-1)%p=n^(f(n-1)%phi(p)+phi(p))%p;再递归地求f(n-1)%phi(p)
当n<=5时,f(n)%p=n^f(n-1)%p,因为不一定有f(n-1)>phi(p)成立,所以不能用欧拉降幂定理求,直接手动求出f(n)%p即可;
从1e9递归到5很慢,但当p=1时,可以直接返回f(n)%p=0而不用递归到下一层;
AC代码:
#include <cstdio>
long long n,m;
long long mod;
long long phi(long long x)
{
    long long res=x;
    for(long long i=2; i*i<=x; ++i)
    {
        if(x%i==0)
        {
            res=res-res/i;
            while(x%i==0)
                x/=i;
        }
    }
    if(x>1)
        res=res-res/x;
    return res;
}
long long qpow(long long a,long long n,long long mod)
{
    long long res=1;
    while(n)
    {
        if(n&1)
        {
            res*=a;
            res%=mod;
        }
        n>>=1;
        a=(a*a)%mod;
    }
    return res;
}
long long solve(long long n,long long m)
{
    if(m==1) return 0;
    if(n==1) return 1;
    else if(n==2) return 2%m;
    else if(n==3) return 9%m;
    else if(n==4) return qpow(4,9,m);
    long long tem=phi(m);
    return qpow(n,solve(n-1,tem)+tem,m);
}
int main()
{
    while(~scanf("%lld%lld",&n,&m))
    {
        printf("%lld
",solve(n,m));
    }
    return 0;
}

以上是关于[数学][欧拉降幂定理]Exponial的主要内容,如果未能解决你的问题,请参考以下文章

Exponial (欧拉定理+指数循环定理+欧拉函数+快速幂)

欧拉定理拓展欧拉定理及其应用(欧拉降幂法)

欧拉函数&欧拉定理&降幂 总结

扩展欧拉定理降幂

[扩展欧拉定理例题]降幂大法

欧拉降幂欧拉定理子序列权值乘积