2019杭电多校第三场

Fansblog

由威尔逊定理可得(p-1)!% p = p-1,那么我们可以从中一直找,找到比p小的最大的质数,然后 Q ! % p = (p-1) * inv ( p-1 ) % p * inv ( p-2 )%p …… * inv ( Q+1 )%p;

# include <bits/stdc++.h>
using namespace std;

typedef long long LL;
LL qmul(LL a,LL b,LL m)
{
	LL ans=0;
	for(;b;b>>=1){
		if(b&1) ans=(ans+a)%m;
		a=(a+a)%m;
	}
	return ans;
}
LL quick_pow(LL a,LL b,LL mod)
{
	LL ret=1;
	while(b)
	{
		if(b&1) ret=qmul(ret,a,mod);
		a=qmul(a,a,mod);
		b=b/2; 
	}
	return ret;
}
inline bool Is_prime(LL n)
{
	if(n==1) return false;
	for(LL i=2;i*i<=n;i++){
		if(n%i==0) return false;
	}
	return true;
}
int main()
{
	int T;
	scanf("%d",&T);
	while(T--){
		LL p;
		LL ans=1;
		scanf("%lld",&p);
		ans=p-1;
		for(LL i=p-1;;i--){
			if(Is_prime(i)) break;
			ans=qmul(ans,quick_pow(i,p-2,p),p);
		}
		printf("%lld\n",ans);
	}
	
	return 0;
 } 
posted @ 2022-02-26 23:24  fengzlj  阅读(25)  评论(0)    收藏  举报