結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー bayashi-clbayashi-cl
提出日時 2022-11-26 11:02:07
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 279 ms / 9,973 ms
コード長 1,513 bytes
コンパイル時間 696 ms
コンパイル使用メモリ 76,764 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-07-25 21:19:26
合計ジャッジ時間 2,381 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ(β)

テストケース

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

ソースコード

diff #

#include <array>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <limits>

using i32 = std::int32_t;
using i64 = std::int64_t;
using i128 = __int128_t;

constexpr i64 mod_pow(i64 p, i64 q, i64 mod) {
    if (mod == 1) return 0;
    i64 res = 1;
    i64 b = p % mod;
    while (q) {
        if (q & 1) res = ((i128)res * b) % mod;
        b = ((i128)b * b) % mod;
        q >>= 1;
    }
    return res;
}

namespace impl {
template <std::size_t N>
constexpr bool miller_rabin(i64 n, std::array<i64, N> bases) {
    auto d = n - 1;
    while (d % 2 == 0) d >>= 1;
    for (auto b : bases) {
        if (n <= b) break;
        auto t = d;
        auto y = mod_pow(b, t, n);
        while (t != n - 1 && y != 1 && y != n - 1) {
            y = (i128)y * y % n;
            t <<= 1;
        }
        if (y != n - 1 && t % 2 == 0) {
            return false;
        }
    }
    return true;
}
}  // namespace impl

constexpr bool is_prime(i64 n) {
    if (not(n & 1)) return n == 2;
    if (n <= 1) return false;
    if (n <= std::numeric_limits<int>::max()) {
        std::array<i64, 3> bases = {2, 7, 61};
        return impl::miller_rabin(n, bases);
    } else {
        std::array<i64, 7> bases = {2, 325, 9375, 28178, 450775, 9780504, 1795265022};
        return impl::miller_rabin(n, bases);
    }
}

int main() {
    i32 n;
    std::cin >> n;
    for (i32 i = 0; i < n; ++i) {
        i64 x;
        std::cin >> x;
        std::cout << x << (is_prime(x) ? " 1" : " 0") << std::endl;
    }
}
0