扩展欧拉定理

注意φ(m)的求法 和细节处理

#include<bits/stdc++.h>
using namespace std;
#define int long long
int a,m;
void MOD(int& x) {
	x=(x%m+m)%m;
}
string s;
int qpow(int a,int b) {
	int tmp=1;
	while(b) {
		if(b&1)tmp*=a,MOD(tmp);
		b>>=1;
		a=a*a,MOD(a);
	}
	return tmp;
}
signed main() {
	cin>>a>>m;
	MOD(a);
	int mm=m;//calculate φ(m)
	int phi=1;
	for(int i=2; i*i<=mm; i++) {
		if(mm%i==0) {
			phi*=(i-1);
			mm/=i;
			while(mm%i==0) {
				phi*=i;
				mm/=i;
			}
		}
	}
	if(mm>1)phi*=(mm-1);
	int bm=0;
	char ch=getchar();
	while(ch<'0'||ch>'9')ch=getchar();
	int flag=0;
	while(ch>='0'&&ch<='9') {
		bm=(int)10*bm+ch-'0';
		if(bm>phi)flag=1,bm=(bm%phi+phi)%phi;
		ch=getchar();
	}
	if(bm>=phi)flag=1,bm=(bm%phi+phi)%phi;
	if(flag)bm+=phi;
	int ans=qpow(a,bm);
	MOD(ans);
	cout<<ans<<"\n";
	return 1+1==3;
}
posted @ 2023-06-09 18:15  N0zoM1z0  阅读(5)  评论(0编辑  收藏  举报