結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー lorent_kyoprolorent_kyopro
提出日時 2020-12-24 00:25:04
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 437 ms / 9,973 ms
コード長 1,069 bytes
コンパイル時間 2,138 ms
コンパイル使用メモリ 200,676 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-28 09:40:59
合計ジャッジ時間 3,887 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
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 237 ms
5,376 KB
testcase_05 AC 224 ms
5,376 KB
testcase_06 AC 76 ms
5,376 KB
testcase_07 AC 77 ms
5,376 KB
testcase_08 AC 77 ms
5,376 KB
testcase_09 AC 437 ms
5,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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

long long pow_mod(long long x, long long n, long long m) {
    assert(0 <= n && 1 <= m);
    if (m == 1) return 0;
    __int128 r = 1, y = (x % m + m) % m;
    while (n > 0) {
        if (n & 1) r = r * y % m;
        y = y * y % m;
        n >>= 1;
    }
    return r;
}

bool is_prime(long long n) {
    if (n <= 1) return false;
    constexpr long long bases[12] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37};
    for (long long a : bases) if (n == a) return true;
    if (n % 2 == 0) return false;
    long long d = n - 1;
    while (d % 2 == 0) d /= 2;
    for (long long a : bases) {
        if (a >= n) break;
        long long t = d;
        __int128 y = pow_mod(a, d, n);
        while (t != n - 1 && y != 1 && y != n - 1) {
            y = y * y % n;
            t <<= 1;
        }
        if (y != n - 1 && t % 2 == 0) return false;
    }
    return true;
}

int main() {
    int n;
    cin >> n;
    while (n--) {
        long long x;
        cin >> x;
        cout << x << ' ' << is_prime(x) << '\n';
    }
}
0