【威尔逊定理+快速乘】hdu2019多校第三场 6608 Fansblog

4 篇文章 0 订阅
1 篇文章 0 订阅

http://acm.hdu.edu.cn/showproblem.php?pid=6608

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

 

Source

2019 Multi-University Training Contest 3

给你一个1e10-1e14之间的素数p,问你刚好小于他的素数q的阶乘%p的余数是多少

解法:威尔逊定理——(p-1)!% p==p-1,(p-2)!%p==1

我们直接找到他,逆元乘回去就好

#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll mod;

ll quickMul(ll a,ll b)
{
    ll res=0;
    while(b)
    {
        if(b&1) res=(res+a)%mod;
        a=(a+a)%mod;
        b>>=1;
    }
    return res;
}

ll quickPow(ll a,ll b)
{
    ll ret=1;
    while(b)
    {
        if(b&1) ret=quickMul(ret,a);
        a=quickMul(a,a);
        b/=2;
    }
    return ret;
}

bool check(ll k)
{
    for(ll i=2;i*i<=k;i++)
    {
        if(k%i==0)
        {
            return 0;
        }
    }
    return 1;
}

ll Find(ll p)
{
    for(ll i=p-1;i>=2;i--)
    {
        if((i%6==1||i%6==5)&&check(i))
        {
            return i;
        }
    }
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        ll p;
        cin>>p;
        mod=p;
        ll q=Find(p);
        ll ans=1;
        for(ll i=q+1;i<=p-2;i++)
        {
            ll t=quickPow(i,p-2);
            ans=quickMul(ans,t);
        }
        printf("%lld\n",ans);
    }

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值