补充个知识点:
快速幂中 我们经常会做取模运算
一般 a%mod 我们会写成 (a+mod)%mod
因为运算过程中 a可能会变成0
而 程序在除法的分母为0或用0取模时会出现算术异常 也就会出现垃圾值 导致RE
快速幂
原理就不解释了
网上很多
留个快速幂模板
//快速幂取模
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll pow_mod(ll x,ll n,ll mod)
{
ll res=1;
while(n)
{
if(n&1==1)
res=res*x%mod;
x=x*x%mod;
n=n/2;
}
return res;
}
int main()
{
ll x,n,mod;
cin>>x>>n>>mod;
ll res;
res=pow_mod(x,n,mod);
cout<<res;
}
快速乘+快速幂
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll x,n,mod;
ll mul(ll a,ll b){
a%=mod;b%=mod;
ll c=(long double)a*b/mod;
ll ans=a*b-c*mod;
return ans<0?ans+mod:ans;
}
ll pow_mod(ll x,ll n){
ll res=1;
while(n){
if(n&1)
res=mul(res,x);
x=mul(x,x);
n>>=1;
}
return res;
}
int main(){
cin>>x>>n>>mod;
cout<<pow_mod(x,n);
}