結果

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

テストケース

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

ソースコード

diff #

#include <initializer_list>

bool IsPrime(unsigned long long x) noexcept {
    if(x <= 1) return false;
    if(x % 2 == 0) return x == 2;
    using u64 = unsigned long long;
    using u128 = __uint128_t;
    u64 d = x-1;
    int s = 0;
    int q = 63;
    while(!(d&1)){ d >>= 1; s++; }
    while(!(d >> q)) q--;
    u64 r = x; for(int t=0; t<5; t++) r*=2-r*x;
    u64 n2 = -(u128)x % x;
    auto red = [=](u128 t) noexcept -> u64 {
        t = (t + (u128)((u64)t*-r)*x) >> 64;
        return (t >= x) ? t-x : t;
    };
    u64 one = red(n2);
    for(u64 base : { 2, 325, 9375, 28178, 450775, 9780504, 1795265022 }){
        if(base%x==0) continue;
        u64 a = base = red((u128)(base%x)*n2);
        for(int e=q-1; e>=0; e--){ a = red((u128)a*a); if((d>>e)&1) a = red((u128)a*base); }
        if(a == one) continue;
        for(int t=1; t<s&&a!=x-one; t++) a = red((u128)a*a);
        if(a != x-one) return false;
    }
    return true;
}

#include <cstdio>

int main(){
    int T; scanf("%d", &T);
    for(int i=0; i<T; i++){
        unsigned long long N; scanf("%llu", &N);
        bool ans = IsPrime(N);
        printf("%llu %s", N, ans ? "1\n" : "0\n");
    }
    return 0;
}
0