2019 Multi-University Training Contest 3 T6 - Fansblog

Fansblog

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,每一次询问\(s!\%p,(s\text{为小于p的最大质数})\)

题解

定理:\((p-1)!\equiv p-1 \space(\mod p)\),p 为质数。

并且,质数以ln分配。

所以,$ans \sum_{i=s+1}^{p-1}i\equiv p-1(\mod p) $

所以,$ ans\equiv p-1\sum_{i=s+1}{p-1}i(\mod p) $

代码

#include<bits/stdc++.h>
#define int long long
using namespace std;
int prime[10]={2,3,5,7,11,13,19,61,2333,24251};
long long M;
int Quick_Multiply(int a,int b,int c) 
{
    long long ans=0,res=a;
    while(b)
    {
        if(b&1)
          ans=(ans+res)%c;
        res=(res+res)%c;
        b>>=1;
    }
    return (int)ans;
}
int Quick_Power(int a,int b,int c) 
{
    int ans=1,res=a;
    while(b)
    {
        if(b&1)
          ans=Quick_Multiply(ans,res,c);
        res=Quick_Multiply(res,res,c);
        b>>=1;
    }
    return ans;
}
bool Miller_Rabin(int x)
{
    int i,j,k;
    int s=0,t=x-1;
    if(x==2)  return true;
    if(x<2||!(x&1))  return false;   
    while(!(t&1))
    {
        s++;
        t>>=1;
    }
    for(i=0;i<10&&prime[i]<x;++i)
    {
        int a=prime[i];
        int b=Quick_Power(a,t,x); 
        for(j=1;j<=s;++j) 
        {
            k=Quick_Multiply(b,b,x); 
            if(k==1&&b!=1&&b!=x-1)
              return false;
            b=k;
        }
        if(b!=1)  return false;
    }
    return true; 
}
signed main()
{
	int T;
	cin >> T;
	while (T--){
    int x;
	int ans;
    scanf("%lld",&x);
	ans = x - 1;
	int M = x;
	while (Miller_Rabin(x-1) == 0) x--, ans = Quick_Multiply(ans, Quick_Power(x,M-2,M),M);
	cout << ans << endl;
	}
	return 0;
}
posted @ 2019-07-29 15:01  dgklr  阅读(152)  评论(0编辑  收藏  举报