2019hdu多校 Fansblog

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

Solution:

通过严谨的计算(打表)可以发现,对于一个质数\(p\),有\((p-1)!\,mod\,p=p-1\)

并且我们知道对于一个质数\(p\),在\(log \,p\)次内可以找到比它小的最大的质数

那么我们每次只要判断当前数是不是质数,再把它除掉,也就是乘上它的逆元,就行了

Code:

#include<bits/stdc++.h>
#define int long long 
using namespace std;
int read(){
    int x=0,f=1;char ch=getchar();
    while(!isdigit(ch)){if(ch=='-')f=-f;ch=getchar();}
    while(isdigit(ch)){x=x*10+ch-48;ch=getchar();}
    return x*f;
}
int isprime(int x){
    if(x<2) return 0;
    for(int i=2;i*i*1ll<=x;i++)
        if(x%i==0) return 0;
    return 1;
}
int dqy(int a,int b,int p){
    int ans=0;
    while(b){
        if(b&1)ans=(ans+a)%p;
        a=(a+a)%p;
        b>>=1;
    }
    return ans;
}
int quick(int a,int b,int p){
    int re=1;
    while(b){
        if(b&1) re=dqy(re,a,p);
        a=dqy(a,a,p);b>>=1;
    }return re%p;
}
void solve(){
    int p=read(),ans=p-1;
    for(int x=p-1;x;x--){
        if(isprime(x)) break;
        ans=dqy(ans,quick(x,p-2,p),p);
    }printf("%lld\n",ans);
}
signed main(){
    int t=read();
    while(t--) solve();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/NLDQY/p/11268072.html