結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー legosukelegosuke
提出日時 2020-12-21 09:28:51
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 1,118 ms / 9,973 ms
コード長 2,085 bytes
コンパイル時間 2,062 ms
コンパイル使用メモリ 201,372 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-08-10 16:27:46
合計ジャッジ時間 5,218 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>
#define int int64_t
using namespace std;

/**
 * @brief 大きな mod 上の計算
 * @note O(1)
 */
inline std::uint64_t mod(std::int64_t a, std::uint64_t m) {
    return (a % m + m) % m;
}

/**
 * @note O(1)
 */
inline std::uint64_t mul(std::int64_t a, std::int64_t b, std::int64_t m) {
    __uint128_t am = mod(a, m), bm = mod(b, m);
    return std::uint64_t(am * bm % m);
}

/**
 * @brief 累乗 : $a^n\bmod{m}$ ($m$ が大きい場合)
 * @note O(\log{n}\log{m})
 */
std::uint64_t mod_pow(std::int64_t a, std::uint64_t n, std::uint64_t m) {
    a = mod(a, m);
    std::uint64_t res = 1;
    while (n) {
        if (n & 1) res = mul(res, a, m);
        a = mul(a, a, m);
        n >>= 1;
    }
    return res;
}

struct Random {
    std::mt19937_64 mt;
    Random() { mt.seed(std::chrono::steady_clock::now().time_since_epoch().count()); }
} rnd;

/**
 * @brief 乱数 (数)
 * @note O(1)
 */
template <typename T>
T random_number(const T a, const T b) {
    assert(a < b);
    if (std::is_integral<T>::value) {
        std::uniform_int_distribution<T> dist(a, b - 1);
        return dist(rnd.mt);
    } else {
        std::uniform_real_distribution<> dist(a, b);
        return dist(rnd.mt);
    }
}

/**
 * @note O(1)
 */
template <typename T>
T random_number(const T b) {
    return random_number(T(0), b);
}

/**
 * @brief 素数判定 (ミラー・ラビン)
 * @note O(k\log^3{n})
 */
bool is_prime(std::uint64_t n, std::uint32_t k = 20) {
    if (n == 2) return true;
    if (n < 2 || !(n & 1)) return false;
    std::uint64_t d = n - 1;
    while (!(d & 1)) d >>= 1;
    for (std::uint32_t i = 0; i < k; ++i) {
        std::uint64_t a = random_number((std::uint64_t)1, n), t = d, y = mod_pow(a, t, n);
        while (t != n - 1 && y != 1 && y != n - 1) {
            y = mod_pow(y, 2, n);
            t <<= 1;
        }
        if (y != n - 1 && !(t & 1)) return false;
    }
    return true;
}

signed main() {
    int n; cin >> n;
    for (int i = 0; i < n; ++i) {
        int x; cin >> x;
        cout << x << " " << is_prime(x) << endl;
    }
}
0