快速幂
参考资料
快速幂
ll Pow(ll x,ll y)
{
x%=mod;
ll res=1;
while(y)
{
if(y&1)res=res*x%mod;
x=x*x%mod;
y>>=1;
}
return res;
}
快速乘
用于计算 ,可以防止 过大溢出。
ll mul(ll x,ll y)
{
x%=mod;
ll res=0;
while(y)
{
if(y&1)res=(res+x)%mod;
x=(x+x)%mod;
y>>=1;
}
return res;
}
例题
洛谷 P1226 【模板】快速幂
给定三个整数 ,求 。()
Reference Code
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
int mod;
ll Pow(ll x,ll y)
{
x%=mod;
ll res=1;
while(y)
{
if(y&1)res=res*x%mod;
x=x*x%mod;
y>>=1;
}
return res;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
ll a,b;
cin>>a>>b>>mod;
cout<<a<<'^'<<b<<" mod "<<mod<<'='<<Pow(a,b)<<'\n';
return 0;
}