zstu 2426 大范围内素数判断(这里用 Miller_Rabin 进行判定)

题目:http://acmpj.zstu.edu.cn/JudgeOnline/showproblem?problem_id=2426

题目大意:给你一个数 n <= 1000000,然后让你判断是不是素数,是就输出"Yes",否则就是"No"。

思路:刚听说了 Miller_Rabin 素数测试,就拿这道题试了一下,测试数 50 左右很保险,但是超时,然后改了一下,20 就过了。

代码如下:

#include<cstdio>
#include<cstring>
#include<time.h>
#include<algorithm>
using namespace std;

typedef __int64 lld;

lld quick_mod(lld a,lld b,lld c)
{
    lld ans = 1;
    while(b)
    {
        if(b&1) ans = (ans*a)%c;
        a = (a*a)%c;
        b >>= 1;
    }
    return ans;
}

lld witness(lld a,lld n)
{

    lld q = n-1;
    int k = 0;
    while(!(q&1))
    {
        k++;
        q >>= 1;
    }
    lld x = quick_mod(a,q,n);
    if(x == 1 || x == n-1) return 1;
    while(k--)
    {
        if(x == n-1) return 1;
        x = (x*x)%n;
    }
    return 0;
}

lld miller_rabin(lld n,int test)//test 为测试组数
{
    if(n <= 1) return 0;
    else if(n == 2) return 1;
    if(!(n&1)) return 0;
    while(test--)
    {
        lld a = rand()*(n-2)/RAND_MAX+1;
        if(!witness(a,n)) return 0;
    }
    return 1;
}

int main()
{
    srand(time(NULL));
    lld n;
    while(~scanf("%I64d",&n))
    {
        if(miller_rabin(n,20)) puts("Yes");
        else puts("No");
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值