[數學][歐拉降冪定理]Exponial

來源:互聯網
上載者:User

標籤:col   題目   struct   ret   out   pre   top   can   positive   

題目描述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\n",solve(n,m));    }    return 0;}

[數學][歐拉降冪定理]Exponial

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.