結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー 👑 MizarMizar
提出日時 2022-08-27 20:16:42
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 224 ms / 9,973 ms
コード長 1,337 bytes
コンパイル時間 157 ms
コンパイル使用メモリ 33,152 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-28 09:59:27
合計ジャッジ時間 1,274 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <cstdio>
#include <cstdbool>
#include <cstdint>
const uint64_t bases[] = {2,325,9375,28178,450775,9780504,1795265022};
uint64_t modpow(uint64_t b, uint64_t p, uint64_t n) {
    if (p == 2) { return (uint64_t)(((__uint128_t)b) * ((__uint128_t)b) % ((__uint128_t)n)); }
    uint64_t r = ((p & 1) == 0) ? 1 : b;
    for (p >>= 1; p != 0; p >>= 1) {
        b = (uint64_t)(((__uint128_t)b) * ((__uint128_t)b) % ((__uint128_t)n));
        if ((p & 1) == 1) { r = (uint64_t)(((__uint128_t)r) * ((__uint128_t)b) % ((__uint128_t)n)); }
    }
    return r;
}
bool miller_rabin(uint64_t n) {
    if (n == 2) { return true; }
    if (n < 2 || (n & 1) == 0) { return false; }
    uint64_t n1 = n - 1, d = n - 1;
    int s = 0;
    while ((d & 1) == 0) { d >>= 1; s += 1; }
    for (int i = 0; i < 7; ++i) {
        uint64_t a = bases[i] % n;
        if (a == 0) { continue; }
        uint64_t t = modpow(a, d, n);
        if (t == 1 || t == n1) { continue; }
        for (int j = 1; j < s; ++j) { t = modpow(t, 2, n); if (t == n1) { goto nextbases; } }
        return false;
        nextbases: continue;
    }
    return true;
}
int main(int argc, char *argv[]) {
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; ++i) {
        int64_t x;
        scanf("%lld", &x);
        printf("%lld %d\n", x, miller_rabin(x) ? 1 : 0);
    }
}
0