【hihocoder 1287】 数论一·Miller-Rabin质数测试

【题目链接】:http://hihocoder.com/problemset/problem/1287

【题意】

【题解】

这里写图片描述
这里写图片描述
取的底数必须是小于等于n-1的;
那12个数字能通过2^64以内的所有数字;

【Number Of WA

0

【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const LL test[12] = {2,3,5,7,11,13,17,19,23,29,31,37};
const double pi = acos(-1.0);
const int N = 110;

int t;

LL multi(LL a,LL b,LL p)
{
    LL ret = 0;
    while (b)
    {
        if (b&1) ret = (ret+a)%p;
        a = (a<<1)%p;
        b>>=1;
    }
    return ret;
}

LL ksm(LL a,LL b,LL p)
{
    LL t = 1;
    while (b)
    {
        if (b&1) t = multi(t,a,p);
        a = multi(a,a,p);
        b>>=1;
    }
    return t;
}

bool miller_rabin(LL n)
{
    if (n==2) return true;
    if (n<2 || ((n&1)==0)) return false;
    LL m = (n-1);
    int k = 0;
    while ((m&1)==0)
    {
        k++;
        m>>=1;
    }
    rep1(i,0,11)
    {
        LL a = test[i];
        if (a>n-1) break;
        LL t = ksm(a,m,n);
        rep1(i,1,k)
        {
            LL y = multi(t,t,n);
            if (y==1 && t!=1 && t!=n-1) return false;
            t = y;
        }
        if (t!=1) return false;
    }
    return true;
}

int main()
{
    ios::sync_with_stdio(false),cin.tie(0);//scanf,puts,printf not use
    cin >> t;
    while (t--)
    {
        LL a;
        cin >> a;
        if (miller_rabin(a))
            cout <<"Yes"<<endl;
        else
            cout <<"No"<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/AWCXV/p/7626368.html