快速幂
参考资料
快速幂
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;
}
另外两种实现:
- __int128
- long double
ll mul(ll a,ll b,ll mod)
{
return __int128(a)*b%mod;
}
ll mul(ll a,ll b,ll mod)
{
return (a*b-ll(ld(a)/mod*b+0.5)*mod+mod)%mod;
}
例题
洛谷 P1226 【模板】快速幂
给定三个整数 ,求 。()
Code (1)
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
ll Pow(ll a,ll b,ll mod)
{
a%=mod;
ll res=1;
while(b)
{
if(b&1)res=res*a%mod;
a=a*a%mod;
b>>=1;
}
return res;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
ll a,b,mod;
cin>>a>>b>>mod;
cout<<a<<'^'<<b<<" mod "<<mod<<'='<<Pow(a,b,mod)<<'\n';
return 0;
}