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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章