hdu 6608 米勒罗宾&&威尔逊定理&&逆元

hdu 6608

求阶乘对一个大质数取模

威尔逊定理:当p是质数时,满足 (p-2)!\equiv1(mod p)

注意米勒罗宾的写法,小心溢出

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int Times = 15;
LL multi(LL a,LL b,LL mod)
{
    LL ans=0;
    while(b)
    {
        if(b&1) ans=(ans+a)%mod;
        b>>=1;
        a=(a%mod+a%mod)%mod;
    }
    return ans;
}
LL pow_mod(LL a,LL b,LL mod)
{
    LL ans=1;
    while(b)
    {
        if(b&1) ans=multi(ans,a,mod);
        b>>=1;
        a=multi(a,a,mod);
    }
    return ans;
}
bool Witness(LL a,LL n)
{
    LL m = n-1;
    int j=0;
    while(!(m&1))
    {
        j++;
        m>>=1;
    }
    LL x = pow_mod(a,m,n);
    if(x==1||x==n-1)
    {
        return false;
    }
    while(j--)
    {
        x = multi(x,x,n);
        if(x==n-1)
        {
            return false;
        }
    }
    return true;
}
LL random(LL n)
{
    return (LL)((double)rand()/RAND_MAX*n+0.5);
}
bool miller_rabin(LL n)
{
    if(n<2) return false;
    if(n==2) return true;
    if(!(n&1)) return false;
    for(int i=1;i<=Times;i++)
    {
        LL a = random(n-2)+1;
        if(Witness(a,n)) return false;
    }
    return true;
}
LL cal(LL solve,LL n)
{
    if(solve==n-2) return 1;
    LL x=1;
    for(LL i=solve+1;i<=n-2;i++)
    {
        x = multi(x,i,n);
    }
    return 1l*pow_mod(x,n-2,n);
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        LL n;
        scanf("%lld",&n);
        LL solve;
        for(LL i = n-1;;i--)
            if(miller_rabin(i)) {
                solve=i;
                break;
        }
//        cout<<solve<<endl;
        printf("%lld\n",cal(solve,n));
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值