結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー firiexpfiriexp
提出日時 2020-02-26 09:37:14
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
WA  
(最新)
AC  
(最初)
実行時間 -
コード長 2,101 bytes
コンパイル時間 762 ms
コンパイル使用メモリ 83,416 KB
実行使用メモリ 6,816 KB
最終ジャッジ日時 2024-05-03 10:09:47
合計ジャッジ時間 1,250 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <limits>
#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){
    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(p >= n) break;
        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