时间限制: 1 Sec 内存限制: 128 MB
题目描述
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.
样例输入
1
1000000007
样例输出
328400734
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll mul(ll a,ll b,ll mod)
{
a%=mod;
b%=mod;
ll res=0;
while(b)
{
if(b&1)
{
res+=a;
if(res>=mod)
res-=mod;
}
b>>=1;
a<<=1;
if(a>=mod)
a-=mod;
}
return res;
}
ll quickPow(ll a,ll b,ll m)
{
ll res=1;
while(b)
{
if(b&1)
res=mul(res,a,m);
a=mul(a,a,m);
b>>=1;
}
return res;
}
int main()
{
int T;
ll ans;
ll Q,P;
bool flag;
scanf("%d",&T);
while(T--)
{
scanf("%lld",&P);
Q=P;
while(1)
{
ans=1;
Q--;
flag=true;
for(ll i=2; i<=sqrt(Q); i++)
{
if(Q%i==0)
{
flag=false;
break;
}
}
if(flag)
{
break;
}
}
Q++;
while(1)
{
if(Q==P-1)
break;
else
ans=mul(ans,Q,P);
Q++;
}
printf("%lld\n",quickPow(ans,P-2,P)%P);
}
return 0;
}
/**************************************************************
Problem: 12969
User: reserve2018058
Language: C++
Result: 正确
Time:818 ms
Memory:2036 kb
****************************************************************/