快速幂

链接:https://ac.nowcoder.com/acm/contest/3800/A
来源:牛客网

题目描述

找到了心仪的小姐姐月月后,华华很高兴的和她聊着天。然而月月的作业很多,不能继续陪华华聊天了。华华为了尽快和月月继续聊天,就提出帮她做一部分作业。
月月的其中一项作业是:给定正整数A、B、P,求ABmod  PA^Bmod PABmodP的值。华华觉得这实在是毫无意义,所以决定写一个程序来做。但是华华并不会写程序,所以这个任务就交给你了。
因为月月的作业很多,所以有T组询问。

输入描述:

第一行一个正整数T表示测试数据组数。
接下来T行,每行三个正整数A、B、P,含义如上文。

输出描述:

输出T行,每行一个非负整数表示答案。
示例1

输入

复制
2
2 5 10
57284938291657 827493857294857 384729583748273

输出

复制
2
18924650048745

备注:

来源:牛客网

1T1e3,1≤A,B,P≤1e18;
注意这个数据范围:1e18
#include<bits/stdc++.h>
using namespace std;
long long mul(long long a,long long b,long long mod)
{
    long long ans=0;
    while(b)
    {
        if(b&1) ans=(ans+a)%mod;
        a=(a+a)%mod;
        b>>=1;
    }
    return ans;
}
long long pow_mod(long long a,long long b,long long mod)
{
    long long ans=1;
  
    while(b)
    {
        if(b&1) ans=mul(ans,a,mod);
        a=mul(a,a,mod);
        b>>=1;
    }
    return ans;
}
int main()
{
    long long t,a,b,p;
    cin>>t;
    while(t--)
    {
        cin>>a>>b>>p;
        cout<<pow_mod(a,b,p)<<endl;
    }
    return 0;
}
 实例2:

aa 的 bb 次方对 pp 取模的值。

输入格式

三个整数 a,b,pa,b,p ,在同一行用空格隔开。

输出格式

输出一个整数,表示a^b mod p的值。

数据范围

0a,b,p1e9:

样例:

3 2 7

输出样例:

2
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int,int> pr;
inline int read() {int x=0,f=1;char c=getchar();while(c!='-'&&(c<'0'||c>'9'))c=getchar();if(c=='-')f=-1,c=getchar();while(c>='0'&&c<='9')x=x*10+c-'0',c=getchar();return f*x;}

const int maxn = 1e6+7;
const int inf = 0x3f3f3f3f;
const int mod = 1e8+7;
int main()
{
    ll a,b,c;
    cin>>a>>b>>c;
    ll sum=1ll*1%c;
    while(b){
        if(b%2)
        sum=sum*1ll*a%c;
        a=a*1ll*a%c;
        b/=2;
    }
    printf("%lld",sum);
}
 
 
原文地址:https://www.cnblogs.com/lipu123/p/12165404.html