結果

問題 No.8030 ミラー・ラビン素数判定法のテスト
ユーザー firiexp
提出日時 2021-03-26 19:22:46
言語 C++17(gcc12)
(gcc 12.3.0 + boost 1.87.0)
結果
WA  
(最新)
CE  
(最初)
実行時間 -
コード長 2,076 bytes
コンパイル時間 4,054 ms
コンパイル使用メモリ 119,300 KB
最終ジャッジ日時 2025-01-19 21:49:26
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 9 WA * 1
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <map>
#include <queue>

static const int MOD = 1000000007;
using ll = long long;
using u32 = unsigned;
using u64 = unsigned long long;
using namespace std;

template<class T>
constexpr T INF = ::numeric_limits<T>::max() / 2;

using u128 = __uint128_t;

struct mod64 {
    u64 n;
    static u64 mod, inv, r2;
    mod64() : n(0) {}
    mod64(u64 x) : n(init(x)) {}
    static u64 init(u64 w) { return reduce(u128(w) * r2); }
    static void set_mod(u64 m) {
        mod = inv = m;
        for (int i = 0; i < 5; ++i) inv *= 2 - inv * m;
        r2 = -u128(m) % m;
    }
    static u64 reduce(u128 x) {
        u64 y = u64(x >> 64) - u64((u128(u64(x) * inv) * mod) >> 64);
        return ll(y) < 0 ? y + mod : y;
    };
    mod64& operator+=(mod64 x) { n += x.n - mod; if(ll(n) < 0) n += mod; return *this; }
    mod64 operator+(mod64 x) const { return mod64(*this) += x; }
    mod64& operator*=(mod64 x) { n = reduce(u128(n) * x.n);  return *this; }
    mod64 operator*(mod64 x) const { return mod64(*this) *= x; }
    u64 val() const { return reduce(n); }
};

u64 mod64::mod, mod64::inv, mod64::r2;

bool suspect(u64 a, u64 s, u64 d, u64 n){
    if(mod64::mod != n) mod64::set_mod(n);
    mod64 x(1), xx(a), one(x), minusone(n-1);
    while(d > 0){
        if(d&1) x = x * xx;
        xx = xx * xx;
        d >>= 1;
    }
    if (x.n == one.n) return true;
    for (int r = 0; r < s; ++r) {
        if(x.n == minusone.n) return true;
        x = x * x;
    }
    return false;
}

template<class T>
bool miller_rabin(T n){
    if (n <= 1 || (n > 2 && n % 2 == 0)) return false;
    u64 d = n - 1, s = 0;
    while (!(d&1)) {++s; d >>= 1;}
    static const u64 v[] = {2, 325, 9375, 28178, 450775, 9780504, 1795265022};
    for (auto &&p : v) {
        if(!suspect(p, s, d, n)) return false;
    }
    return true;
}

int main() {
    ll n;
    cin >> n;
    for (int i = 0; i < n; ++i) {
        u64 k; scanf("%lld", &k);
        printf("%lld %d\n", k, miller_rabin(k));
    }
    return 0;
}
0