素性测试

2024-08-14

采用费马素性测试和二次探测定理判断质数

#include <bits/stdc++.h>
#define io cin.tie(0), cout.tie(0), ios::sync_with_stdio(false)
#define LL long long
#define ULL unsigned long long
#define EPS 1e-8
#define INF 0x7fffffff
#define SUB -INF - 1
using namespace std;
LL fast_pow(LL x, LL y, int m)
{
    LL res = 1;
    x %= m;
    while (y)
    {
        if (y & 1)
            res = (res * x) % m;
        x = (x * x) % m;
        y >>= 1;
    }
    return res;
}
bool witness(LL a, LL n)
{
    LL u = n - 1;
    int t = 0;
    while (u & 1 == 0)
        u = u >> 1, t++;
    LL x1, x2;
    x1 = fast_pow(a, u, n);
    for (int i = 1; i <= t; i++)
    {
        x2 = fast_pow(x1, 2, n);
        if (x2 == 1 && x1 != 1 && x1 != n - 1)
            return true;
        x1 = x2;
    }
    if (x1 != 1)
        return true;
    return false;
}
int miller_rabin(LL n, int s)
{
    if (n < 2)
        return 0;
    if (n == 2)
        return 1;
    if (n % 2 == 0)
        return 0;
    for (int i = 0; i < s && i < n; i++)
    {
        LL a = rand() % (n - 1) + 1;
        if (witness(s, n))
            return 0;
    }
    return 1;
}
int main()
{
    int m;
    while (scanf("%d", &m) != EOF)
    {
        int cnt = 0;
        for (int i = 0; i < m; i++)
        {
            LL n;
            scanf("%lld", &n);
            int s = 50;
            cnt += miller_rabin(n, s);
        }
        printf("%d\n", cnt);
    }
    return 0;
}