Miller-Rabin素数检测算法hud 6608(检验一个大整数是不是素数)

 一个博客链接:https://blog.csdn.net/forever_dreams/article/details/82314237

#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <map>
#include <set>
#include <bitset>
#include <stack>
#define ull unsigned long long
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define mems(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long ll;
const ll mod=998244353;
const int N=2e5+10;
const double pi=acos(-1);
const int inf=0x3f3f3f3f;
const int M=50000+5;
ll ModMul(ll a,ll b,ll n)//快速积取模 a*b%n
{
    ll ans=0;
    while(b)
    {
        if(b&1)
            ans=(ans+a)%n;
        a=(a+a)%n;
        b>>=1;
    }
    return ans;
}
ll ModExp(ll a,ll b,ll n)//快速幂取模 a^b%n
{
    ll ans=1;
    while(b)
    {
        if(b&1)
            ans=ModMul(ans,a,n);
        a=ModMul(a,a,n);
        b>>=1;
    }
    return ans;
}
bool miller_rabin(ll n)//Miller-Rabin素数检测算法
{
    ll i,j,a,x,y,t,u,s=10;
    if(n==2)
        return true;
    if(n<2||!(n&1))
        return false;
    for(t=0,u=n-1; !(u&1); t++,u>>=1); //n-1=u*2^t
    for(i=0; i<s; i++)
    {
        a=rand()%(n-1)+1;
        x=ModExp(a,u,n);
        for(j=0; j<t; j++)
        {
            y=ModMul(x,x,n);
            if(y==1&&x!=1&&x!=n-1)
                return false;
            x=y;
        }
        if(x!=1)
            return false;
    }
    return true;
}

ll inv(ll a,ll mod)
{
    return ModExp(a,mod-2,mod);
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        ll n;
        scanf("%lld",&n);
        ll k=n-1;
        while(!miller_rabin(k))
        {
            k--;
        }
        ll ans=1;
        for(k++; k<=n-2; k++)
        {
            ans=ModMul(ans,inv(k,n),n);
        }
        printf("%lld\n",ans);
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值