Time Limit: 2000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 374 Accepted Submission(s): 107
Problem Description
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-2)!%p=1,于是我们得出一个结论(p-2)!%p=1,那么我们若找到一个最接近p的素数q<p(q的寻找方式直接使用最暴力的判断方式for(int i=2;i<sqrt ( p );i++)即可,一开始还头疼怎么判断素数,突然想起来因数从2判断到sqrt§即可,因为是1e14的大数,欧拉筛筛不出来,而且只需判断比p小的下一个素数,两者不会相差太大),就根据结论来简便的求出结果:q!%p=(p-2)!/( (p-3)(p-4) …(q+1) )%p=1 * 1/( (p-3)(p-4) …(q+1) )%p,求逆元即可,只不过不可以直接求模,否则会爆long long ,利用高精度乘法即可,同样的求逆元使用的快速幂也需要使用高精度乘法,否则也会爆;
#include <iostream>
#include <time.h>
#include <fstream>
using namespace std;
typedef unsigned long long ll;
ll mul(ll,ll,ll);
ll qmod(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 mul(ll a,ll b,ll mod)///高精度乘法
{
a%=mod,b%=mod;
ll sum=0;
while(b)
{
if(b&1) sum=(sum+a)%mod;
b>>=1;
a=a*2%mod;
}
sum%=mod;
return sum;
}
ll getfac(ll s,ll e,ll mod)
{
ll f=1;
for(register ll i=s+1;i<=e-2;i++) f=mul(f,i,mod);
f%=mod;
return f;
}
bool judge(ll n)
{
for(register ll i=2;i<=10000000;i++)
{
if(n%i==0) return false;
}
return true;
}
int main()
{
int T;cin>>T;
while(T--)
{
ll n;cin>>n;
register ll p;
for(p=n-1;p;p--)
{
if(judge(p)) break;
}
if(p==n-2) {cout<<1<<endl;continue;}
ll fac=getfac(p,n,n);
//cout<<"prime2="<<p<<endl;
ll ans=qmod(fac,n-2,n)%n;
cout<<ans<<endl;
}
//cout<<mul(100000000000,1000000000041,10000000000000);
return 0;
}
/*
10
1000000007
1000000021
1000000009
1000000033
1000000087
1000000093
1000000097
1000000103
1000000363
*/