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 )
输入
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)
输出
For each testcase, output an integer representing the factorial of Q modulo P.
思路
这个题目目前我知道有两种做法。做法一 暴力求逆元,做法二 用米勒罗宾素数判断。但我现在只会做法一,做法二等有空就去学习。做法二的时间特别短,做法一就有点麻烦了。
首先通过暴力打表或者是威尔逊定理,我们都可以发现当P和Q同为孪生素数的时候,Q!%P=1;
且P-Q>=2。所以我们可以将Q!=(P-2)!/(Q+1)(Q+2)…(P-2);
根据(P-2)!%P==1;那么我们只要算(1/(Q+1)(Q+2)…(P-2) )%P;
那么就是算分母的逆元。但是由于数据范围很大,longlong直接相乘的话会爆,就得把乘法变为加法。
接下来附上AC代码
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
const int N=1e6+5;
typedef long long ll;
ll mul(ll a,ll b,ll mod)
{
ll sum=0;c
a%=mod;b%=mod;
while(b)
{
if(b&1) sum=(sum+a)%mod;
b>>=1;
a=(a*2)%mod;
}
return sum;
}
ll qpow(ll a,ll b,ll mod)
{
ll sum=1;
while(b)
{
if(b&1) sum=mul(sum,a,mod);
b>>=1;
a=mul(a,a,mod);
}
return sum;
}
ll niyuan(ll a,ll b,ll mod)
{
ll sum=1;
for(register ll i=b+1;i<=a-2;i++)
{
sum=mul(sum,i,mod);
}
sum=qpow(sum,a-2,mod);
return sum;
}
bool judge(ll a)
{
for(register ll i=2;i<=10000000;i++)
{
if(a%i==0) return false;
}
return true;
}
int main()
{
int x;
scanf("%d",&x);
register ll p,q;
while(x--)
{
scanf("%lld",&p);
for(q=p-1;;q--)
{
if(judge(q)) break;
}
//cout<<q<<endl;
if(q==p-2) printf("1\n");
else{
ll ans=niyuan(p,q,p);
printf("%lld\n",ans);
}
}
return 0;
}