Fansblog(逆元)

Farmer John keeps a website called ‘FansBlog’ .Everyday , there are many people visited this blog.One day, he find the visits has reached P , which is a prime number.He thinks it is a interesting fact.And he remembers that the visits had reached another prime number.He try to find out the largest prime number Q ( Q < P ) ,and get the answer of Q! Module P.But he is too busy to find out the answer. So he ask you for help. ( Q! is the product of all positive integers less than or equal to n: n! = n * (n-1) * (n-2) * (n-3) *… * 3 * 2 * 1 . For example, 4! = 4 * 3 * 2 * 1 = 24 )
Input
First line contains an number T(1<=T<=10) indicating the number of testcases.
Then T line follows, each contains a positive prime number P (1e9≤p≤1e14)
Output
For each testcase, output an integer representing the factorial of Q modulo P.
Sample Input
1
1000000007
Sample Output
328400734

解题思路

题意就是给一个质数P,找到一个最大的质数Q(Q<P),求Q!mod§.先求出Q,质数打表打到1e7,根据威尔逊定理:(p−1)!modp=p−1≡−1 (mod p) p质数。这道题就可以这样写
Q!* (Q+1) * (Q+2)… (P-2)(P-1)mod P= P-1;
Q!=(P-1)/( (Q+1) * (Q+2)… (P-2)
(P-1) )mod P,然后再用费马小定理求解,这题直接用快速幂会超时,要用快速乘优化一下。

#pragma GCC optimeze(2)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;//这题一定要用ll 
const ll maxn=1e7;
bool prime[maxn+10];
ll p[666666],k=0;
ll mod;
void ss()
{
	prime[0]=prime[1]=1;
	for(ll i=2;i<maxn;i++)
	{
		if(!prime[i])
		{
			p[k++]=i;
			for(ll j=i*i;j<maxn;j+=i)//打表 
			{
				prime[j]=1;
			}
		}
	}
}
int check(ll x)
{
	for(ll i=0;i<k&&p[i]*p[i]<=x;i++)//判断质数 
	{
		if(x%p[i]==0)
		return 0;
	}
	return 1;
}

ll mul(ll a,ll b)
{
	ll ans=0;
	while(b)
	{
		if(b&1) 
		ans=(ans+a)%mod;//快速乘 
		b>>=1;
		a=(a+a)%mod;
	}
	return ans;
}

ll ksm(ll a,ll b)
{
	ll res=1;
	while(b)
	{
		if(b&1)
		res=mul(res,a);//快速幂 
		b>>=1;
		a=mul(a,a);
	}
	return res;
}


int main()
{
	ss();
	int t;
	scanf("%d",&t);
	while(t--)
	{
		ll p;
		scanf("%lld",&p);
		ll ans=p-1;
		mod=p;
		ll q=p-1;//从p-1开始 
		while(!check(q))
		{
			q--;
		}
		for(ll i=q+1;i<p;i++)
		{
			ans=mul(ans,ksm(i,mod-2));//这个就是思路上写的 
		}
		printf("%lld\n",ans);
	}
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值