HDU 2138 How many prime numbers

Miller-Rabin

关于Miller-Rabin算法,可以看http://www.matrix67.com/blog/archives/234

主要是用了费马小定理+二次探测,随机选取k个底数进行测试算法的失误率大概为 4k 。多随机几次就不太容易挂了。

下面代码里的work是用来对拍的根号暴力。

#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
namespace runzhe2000
{
    typedef long long ll;

    bool work(ll x)
    {
        for(ll i = 2, ii = sqrt(x); i <= ii; i++)
            if(x % i == 0) return false;
        return true;
    }

    ll fpow(ll a, int b, ll p)
    {
        ll r = 1;
        for(; b; b>>= 1)
        {
            if(b & 1) (r *= a) %= p;
            (a *= a) %= p;
        }
        return r;
    }
    bool MR(ll n)
    {
        if(n == 2) return 1;
        ll a = n-1, b = 0;
        for(; !(a&1); a >>= 1, b++);
        for(int t = 10; t; t--)
        {
            ll x = rand()%(n-2)+2, pre;
            x = pre = fpow(x, a, n);
            for(int i = 0; i < b; i++)
            {
                (x *= x) %= n;
                if(x % n == 1 && pre != 1 && pre != n-1) return false;
                pre = x;
            }
            if(x % n != 1) return false;
        }
        return true;
    }

    void main()
    {
        int n,ans_MR;
        for(; scanf("%d",&n) != EOF; )
        {
            ans_MR = 0;
            for(; n--; )
            {
                ll x; scanf("%lld",&x);
                ans_MR += MR(x);
            }
            printf("%d\n",ans_MR);
        }
    }
}
int main()
{
    runzhe2000::main();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值