結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー tubo28tubo28
提出日時 2017-10-22 00:12:10
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 234 ms / 9,973 ms
コード長 1,946 bytes
コンパイル時間 1,357 ms
コンパイル使用メモリ 167,104 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-08-10 15:47:29
合計ジャッジ時間 2,898 ms
ジャッジサーバーID
(参考情報)
judge14 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 1 ms
4,376 KB
testcase_03 AC 1 ms
4,380 KB
testcase_04 AC 124 ms
4,376 KB
testcase_05 AC 121 ms
4,376 KB
testcase_06 AC 51 ms
4,376 KB
testcase_07 AC 50 ms
4,376 KB
testcase_08 AC 50 ms
4,376 KB
testcase_09 AC 234 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using u32 = unsigned int;
using u64 = unsigned long long;
using u128 = __uint128_t;

template <class Uint, class BinOp>
bool is_prime_impl(const Uint &n, const Uint *witness, BinOp modmul) {
    if (n == 2) return true;
    if (n < 2 || n % 2 == 0) return false;
    const Uint m = n - 1, d = m / (m & -m);
    auto modpow = [&](Uint a, Uint b) {
        Uint res = 1;
        for (; b; b /= 2) {
            if (b & 1) res = modmul(res, a);
            a = modmul(a, a);
        }
        return res;
    };
    auto suspect = [&](Uint a, Uint t) {
        a = modpow(a, t);
        while (t != n - 1 && a != 1 && a != n - 1) {
            a = modmul(a, a);
            t = modmul(t, 2);
        }
        return a == n - 1 || t % 2 == 1;
    };
    for (const Uint *w = witness; *w; w++) {
        if (*w % n != 0 && !suspect(*w, d)) return false;
    }
    return true;
}

bool is_prime(const u128 &n) {
    assert(n < 1ULL << 63);
    if (n < 1ULL << 32) {
        // n < 2^32
        constexpr u64 witness[] = {2, 7, 61, 0};
        auto modmul = [&](u64 a, u64 b) { return a * b % n; };
        return is_prime_impl<u64>(n, witness, modmul);
    } else {
        // n < 2^63
        constexpr u128 witness[] = {2, 325, 9375, 28178, 450775, 9780504, 1795265022, 0};
        // if u128 is available
        auto modmul = [&](u128 a, u128 b) { return a * b % n; };
        // otherwise
        // auto modmul = [&](u64 a, u64 b) {
        //     u64 res = 0;
        //     for (; b; b /= 2) {
        //         if (b & 1) res = (res + a) % n;
        //         a = (a + a) % n;
        //     }
        //     return res;
        // };
        return is_prime_impl<u128>(n, witness, modmul);
    }
}

using namespace std;

int main() {
    cin.tie(0);
    ios::sync_with_stdio(0);
    int n;
    cin >> n;
    while (n--) {
        u64 x;
        cin >> x;
        cout << x << ' ' << is_prime(x) << '\n';
    }
}
0