結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー dyktr_06dyktr_06
提出日時 2022-09-09 20:24:26
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 258 ms / 9,973 ms
コード長 1,233 bytes
コンパイル時間 1,476 ms
コンパイル使用メモリ 169,156 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-05-04 09:56:31
合計ジャッジ時間 3,035 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

// 素数かどうかを判定します(n <= 2^64 なら必ず成功します) : O(logn)
bool rabin_miller(long long n){
    switch(n){
        case 0: // fall-through
        case 1: return false;
        case 2: return true;
    }

    if(n % 2 == 0) return false;
    vector<long long> A = {2, 325, 9375, 28178, 450775, 9780504, 1795265022};
    long long s = 0, d = n - 1;
    while(d % 2 == 0){
        s++;
        d >>= 1;
    }

    auto modpow = [](__int128_t x, __int128_t e, const __int128_t m) -> __int128_t {
        __int128_t ret = 1 % m;
        x %= m;
        while(e > 0){
            if(e & 1) (ret *= x) %= m;
            (x *= x) %= m;
            e >>= 1;
        }
        return ret;
    };

    for(auto a : A){
        if(a % n == 0) return true;
        long long t, x = modpow(a, d, n);
        if(x != 1){
            for(t = 0; t < s; ++t){
                if (x == n - 1) break;
                x = __int128_t(x) * x % n;
            }
            if(t == s) return false;
        }
    }
    return true;
}

int main(){
    int n; cin >> n;
    while(n--){
        long long x; cin >> x;
        cout << x << " " << 0 + rabin_miller(x) << "\n";
    }
}
0