快速冪模板


 

Description

求a的b次方,取模mod(1<=a,b,mod<=1e18)

Input

多組輸入,每組數據一行,3個正整數,分別為a,b,mod

Output

每組數據輸出一行,為答案 

Sample Input

2 10 10000000
5 100 1
0 2 37

Sample Output

1024
0
0
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

/*long long qmod(ll a,ll b,int c)
{
    if(b==1) return a;
    if(b&1) return a*qmod(a,b-1,c)%c;
    else
    {
        ll m=qmod(a,b/2,c);
        return m*m%c;
    }
    
} */用二分還是超時
ll qmod(ll a,ll b,ll c)//快速冪
{
    int r=1;
    while(b)
    {
        if(b&1) r=a*r%c;
        a=a*a%c;
        b>>=1; b的二進制形式刪除最后一位
    }
    return r;
}
int main()
{
    long long a,b,c;
    cin>>a>>b>>c;
    if(a>c) a=a%c;
    if(c==1) cout<<"0"<<endl;
    else
    {
ll ans
=qmod(a,b,c); cout<<ans<<endl; } }

參考資料: https://blog.csdn.net/qq_42265608/article/details/89475457

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM