[总结] (扩展)欧拉定理
欧拉定理
- 若 \(gcd(a,b)=1\),则 \(a^{\varphi(m)}\equiv 1 \ (mod \ \ m)\)
扩展欧拉定理
- 只能在指数比 \(\varphi(p)\) 大的时候使用(下面第三个)
内容:
- $ a^b\equiv\left{\begin{array}{rcl}
a^{b \ mod \ \varphi(p)} & &{gcd(a,p)=1}\
a^b, & & {gcd(a,p)\not = 1}\
a^{b \ mod \ \varphi(p) +\varphi(p) }& &{gcd(a,p)\not=1} \end{array}\right. \pmod{p}$
只需要记住两点
-
指数比 \(\varphi(p)\) 大的时候就加上 \(\varphi(p)\)
-
注意互质和不互质的情况
下面是模板部分
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#define int long long
using namespace std;
int a,m,b;
char c;
int make_phi(int x){
int phi=x;
int t=(int)sqrt(x+0.5);
for(int i=2;i<=t;i++){
if(x%i==0){
phi=phi-phi/i;
while(x%i==0){
x/=i;
}
}
}
if(x>1){
phi=phi-phi/x;
}
return phi;
}
int power(int a,int b){
int res=1;
while(b){
if(b&1)res=1LL*res*a%m;
a=1LL*a*a%m;
b>>=1;
}
return res;
}
signed main(){
scanf("%lld%lld",&a,&m);
int tmp=m,phi=m;
////////
int phi_m=make_phi(m);
while(!isdigit(c))c=getchar();
bool fl=false;
while(isdigit(c)){
b=b*10LL+c-'0';
if(b>=phi_m){
fl=true;
b%=phi_m;
}
c=getchar();
}
if(fl){
b+=phi_m;//如果指数≥phi,需要加上phi
}
printf("%lld",power(a,b));
return 0;
}