結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー kya_skikya_ski
提出日時 2020-04-05 13:48:21
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 493 ms / 9,973 ms
コード長 2,135 bytes
コンパイル時間 1,607 ms
コンパイル使用メモリ 167,760 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-28 09:29:12
合計ジャッジ時間 3,456 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

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

struct MillerRabin {
    using lint = unsigned long long int;
private : 
    const lint val1 = 4759123141;
    const lint val2 = 341550071728321;
    const lint v1[3] = {2, 7, 61};
    const lint v2[7] = {2, 3, 5, 7, 11, 13, 17};
    const lint v3[7] = {2, 325, 9375, 28178, 450775, 9780504, 1795265022};
public : 
    inline lint mul (lint a, lint b, lint m) {
        return __int128_t(a) * b % m;
    }

    inline lint modpow(lint x, lint k, lint m){
        x %= m;
        lint a = 1, p = x;
        while(k > 0) {
            if (k % 2 == 0) { p = mul(p, p, m); k /= 2; }
            else { a = mul(a, p, m); k--; }
        }
        return a;
    }

    inline bool sub (lint a, lint n, lint d, lint s) {
        bool flag = true;
        for (lint r = 0; r < s; r++) {
            if (modpow(a, d, n) == n - 1) {
                flag = false; break;
            }
            d <<= 1LL;
        }
        return flag;
    }

    bool isprime (lint n) {
        if (n < 2) return false;
        lint d = n - 1, s = 0;
        while (d % 2 == 0) { d /= 2; s++; }
        if (n < val1) {
            for (const lint &a : v1) {
                if (n < a) break;
                if (a == n) return true;
                if (modpow(a, d, n) == 1) continue;
                if (sub(a, n, d, s)) return false;
            }
        } else if (n < val2) {
            for (const lint &a : v2) {
                if (a == n) return true;
                if (modpow(a, d, n) == 1) continue;
                if (sub(a, n, d, s)) return false;
            }
        } else {
            for (const lint &a : v3) {
                if (a == n) return true;
                if (modpow(a, d, n) == 1) continue;
                if (sub(a, n, d, s)) return false;
            }
        }
        return true;
    }

};


int main() {
    ios::sync_with_stdio(0);
    cin.tie(nullptr);
    
    MillerRabin miller;
    
    int q;
    cin >> q;
    
    long long n;
    while (q--) {
        long long n;
        cin >> n;
        cout << n << ' ' << miller.isprime(n) << '\n';
    }
    return 0;
}
0