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
题意:T组样例,每组样例,给出一个素数P(1e9≤P≤1e14),Q是P的前一个素数求Q!%P。
思路:在初等数论中,威尔迅定理给出了判定一个自然数是否为素数的充分必要条件。即:当且仅当p为素数的时候:( p -1 )! -1 ≡( mod p ),但是由于阶乘是呈爆炸增长的,其结论对于实际操作意义不大。
所以:由威尔迅定理得:((p−1)!)%p=q!×(q+1)×(q+2)×...×(p−1)%p=p−1
q!≡(q+1)×(q+2)×...×(p−2)1(mod p)
AC代码:
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 1e7+10;
ll mod;
int prime[N+10],cnt;
bool vis[N+10];
bool is_prime(ll x)
{
for(int i=0;i<cnt&&(ll)prime[i]*prime[i]<=x;i++)
{
if(x%prime[i]==0)
return 0;
}
return 1;
}
void get_prime()
{
for(int i=2;i<=N;i++)
{
if(!vis[i])
prime[cnt++]=i;
for(int j=0;j<cnt&&(ll)i*prime[j]<=N;j++)
{
vis[i*prime[j]]=1;
if(i%prime[j]==0) break;
}
}
}
ll mul(ll a,ll b)
{
ll res=0;
while(b)
{
if(b&1) res=(res+a)%mod;
a=(a+a)%mod;
b>>=1;
}
return res%mod;
}
ll poww(ll a,ll b)
{
ll res=1;
while(b)
{
if(b&1) res=mul(res,a);
a=mul(a,a);
b>>=1;
}
return res;
}
int main(void)
{
int t;
get_prime();
ll p,q;
scanf("%d",&t);
while(t--)
{
scanf("%lld",&p);
mod=p;
q=p-1;
while(!is_prime(q)) q--;
ll ans=p-1;
for(ll i=q+1;i<=p-1;i++)
ans=mul(ans,poww(i,mod-2));
printf("%lld\n",ans);
}
return 0;
}