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
1000000007Sample Output
328400734
题意:t 组样例,每组给出一个素数 p,求一个小于 p 的最大素数 q,输出 q 的阶乘模 p
根据威尔逊定理:
那么有:
由于
于是:
根据质数分布密度定理:素数的分布越来越稀疏,当 1E18 内的任意两个素数的差不会很大
因此可以从 p-1 开始,一个个查验 q,再将 p-1 乘上 的逆元即可
此外,由于数据范围极大,因此所有的乘法都需要利用到快速乘法
Source Program
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<unordered_map>
#include<bitset>
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
#define Pair pair<LL,LL>
LL quickPow(LL a,LL b){ LL res=1; while(b){if(b&1)res*=a; a*=a; b>>=1;} return res; }
LL multMod(LL a,LL b,LL mod){ a%=mod; b%=mod; LL res=0; while(b){if(b&1)res=(res+a)%mod; a=(a<<=1)%mod; b>>=1; } return res%mod;}
LL quickPowMod(LL a, LL b,LL mod){ LL res=1,k=a; while(b){if((b&1))res=multMod(res,k,mod)%mod; k=multMod(k,k,mod)%mod; b>>=1;} return res%mod;}
LL getInv(LL a,LL mod){ return quickPowMod(a,mod-2,mod); }
LL GCD(LL x,LL y){ return !y?x:GCD(y,x%y); }
LL LCM(LL x,LL y){ return x/GCD(x,y)*y; }
const double EPS = 1E-10;
const int MOD = 998244353;
const int N = 10000000+5;
const int dx[] = {-1,1,0,0,1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;
int primes[N],cnt;
bool bPrime[N];
void getPrimes(int n){
memset(bPrime,false,sizeof(bPrime));
for(int i=2;i<=n;i++){
if(!bPrime[i])
primes[cnt++]=i;
for(int j=0;j<cnt&&i*primes[j]<n;j++){
bPrime[i*primes[j]]=true;
if(i%primes[j]==0)
break;
}
}
}
bool judge(LL x){
for(int i=0;i<cnt&&(LL)primes[i]*primes[i]<=x;i++)
if(x%primes[i]==0)
return false;
return true;
}
int main(){
getPrimes(10000000);
int t;
scanf("%d",&t);
while(t--){
LL p;
scanf("%lld",&p);
LL mod=p;
LL q=p-1;
while(!judge(q))
q--;
LL res=p-1;
for(LL i=q+1;i<=p-1;i++)
res=multMod(res,getInv(i,mod),mod);
printf("%lld\n",res);
}
return 0;
}