結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー amylase_pepsinamylase_pepsin
提出日時 2020-10-15 10:06:41
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 720 ms / 9,973 ms
コード長 2,234 bytes
コンパイル時間 1,936 ms
コンパイル使用メモリ 173,012 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-28 09:38:55
合計ジャッジ時間 4,407 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
5,248 KB
testcase_01 AC 2 ms
5,376 KB
testcase_02 AC 2 ms
5,376 KB
testcase_03 AC 2 ms
5,376 KB
testcase_04 AC 392 ms
5,376 KB
testcase_05 AC 389 ms
5,376 KB
testcase_06 AC 165 ms
5,376 KB
testcase_07 AC 167 ms
5,376 KB
testcase_08 AC 167 ms
5,376 KB
testcase_09 AC 720 ms
5,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include "bits/stdc++.h"

#include <vector>

namespace amylase {

using li = __int128_t;
li _powmod(const li x, const li n, const li mod) {
    if (n == 0) {
        return 1;
    }
    li sq = _powmod(x, n / 2, mod);
    if (n & 1) {
        return sq * sq % mod * x % mod;
    } else {
        return sq * sq % mod;
    }
}

bool _miller_rabin(const long long x, const std::vector<long long>& witnesses) {
    if (x <= 1) {
        return false;
    }
    if ((x & 1) == 0) {
        return x == 2;
    }
    long long d = x - 1;
    long long s = 0;
    while ((d & 1) == 0) {
        d >>= 1;
        s++;
    }

    for (const auto& a : witnesses) {
        if (a % x <= 1) {
            continue;
        }
        bool is_composite = true;
        is_composite &= _powmod(a, d, x) != 1;
        long long dd = d;
        for (int i = 0; i < s; ++i) {
            is_composite &= _powmod(a, dd, x) != x - 1;
            dd <<= 1;
        }
        if (is_composite) {
            return false;
        }
    }
    return true;
}

bool is_prime(const long long x) {
    return _miller_rabin(x, {2LL, 325LL, 9375LL, 28178LL, 450775LL, 9780504LL, 1795265022LL});
}

std::vector<long long> factor(long long x) {
    std::vector<long long> factors;
    long long p = 2;
    while (p * p <= x) {
        while (x % p == 0) {
            factors.emplace_back(p);
            x /= p;
        }
        p++;
    }
    if (x > 1) {
        factors.emplace_back(x);
    }
    return factors;
}

/**
 * solves ax + by = gcd(a, b)
 * @param a
 * @param b
 * @param x ref to variable to store root x
 * @param y ref to variable to store root x
 * @return gcd(a, b)
 */
long long extgcd(long long a, long long b, long long& x, long long& y) {
    long long d = a;
    if (b != 0) {
        d = extgcd(b, a % b, y, x);
        y -= (a / b) * x;
    } else {
        x = 1; y = 0;
    }
    return d;
}

}  // namespace amylase


using namespace std;
typedef long long li;

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);

    li n;
    cin >> n;
    for (int i = 0; i < n; ++i) {
        li x;
        cin >> x;
        cout << x << " ";
        li ispr = amylase::is_prime(x);
        cout << ispr << '\n';
    }

    return 0;
}
0