快速幂
下面两种方法的时间复杂度差不多
快速幂之迭代版
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
LL qmi(LL a,LL k,LL p)
{
LL res=1;
while(k)
{
if(k&1)
{
res=(LL)res*a%p;
}
k>>=1;
a=(LL)a*a%p;
}
return res;
}
int main()
{
int T;
cin>>T;
while(T--)
{
LL a,k,p;
scanf("%lld %lld %lld",&a,&k,&p);
cout << qmi(a,k,p)<<endl;
}
return 0;
}
快速幂——递归版
#include<iostream>
using namespace std;
#define ull unsigned long long
ull quick_pow(ull a,ull k,ull p)
{
if(k==0) return 1;
a%=p;
ull res=quick_pow(a,k>>1,p);
if(k&1) return res*res%p*a%p;
return res*res%p;
}
int main()
{
int n;
cin>>n;
while(n--)
{
int a,k,p;
cin.tie(0);
ios::sync_with_stdio(false);
cin>>a>>k>>p;
cout<<quick_pow(a,k,p)<<endl;
}
return 0;
}
欧拉函数
在写ans= ans / i * (i - 1);时若调转顺序,写成ans = ans * (i - 1) / i;
可能会使ans的结果int上溢
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
int T;cin>>T;
while(T--)
{
int N;cin>>N;
int ans=N;
//判断质数的时候这里是<=
for(int i=2;i<=N/i;i++)
{
//如果N能被i表示
if(N%i==0)
{
ans=ans/i*(i-1);//不能加括号
while(N%i==0)N/=i;
}
}
if(N>1)ans=ans/N*(N-1);
cout<<ans<<endl;
}
return 0;
}
快速幂和欧拉函数相结合的题目
这里有个求逆元的题解,有时间也得去学一下AcWing 4968. 互质数的个数(快速幂+乘法逆元+质因数分解+欧拉函数) - AcWing
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int MOD = 998244353;
//快速幂模块
LL qmi(LL a, LL b)
{
LL res = 1;
while (b)
{
if (b & 1) res = res * a % MOD;
a = a * a % MOD;
b >>= 1;
}
return res;
}
int main()
{
LL a, b;
cin >> a >> b;
//特判
if (a == 1)
{
cout << 0 << endl;
return 0;
}
//欧拉函数模块
LL res = a, x = a;
for (int i = 2; i * i <= x; i ++ )
if (x % i == 0)
{
while (x % i == 0) x /= i;
res = res / i * (i - 1);
}
if (x > 1) res = res / x * (x - 1);
cout << res * qmi(a, b - 1) % MOD << endl;
return 0;
}