結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー RTnFRTnF
提出日時 2022-06-11 18:05:55
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 383 ms / 9,973 ms
コード長 1,374 bytes
コンパイル時間 1,738 ms
コンパイル使用メモリ 202,424 KB
実行使用メモリ 6,944 KB
最終ジャッジ日時 2024-04-28 09:50:33
合計ジャッジ時間 3,179 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
6,812 KB
testcase_01 AC 1 ms
6,944 KB
testcase_02 AC 1 ms
6,944 KB
testcase_03 AC 2 ms
6,944 KB
testcase_04 AC 197 ms
6,944 KB
testcase_05 AC 186 ms
6,940 KB
testcase_06 AC 50 ms
6,940 KB
testcase_07 AC 54 ms
6,944 KB
testcase_08 AC 50 ms
6,944 KB
testcase_09 AC 383 ms
6,944 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
using ll = int64_t;
using ull = uint64_t;
using ld = long double;
constexpr ll MOD = 1e9 + 7;
constexpr ll INF = 1e+18;
constexpr ld EPS = 1e-12L;
constexpr ld PI = 3.14159265358979323846L;

// Miller test for 64bit
// https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
bool isPrime(ull n) {
  if(n == 2) {
    return true;
  }
  if(!(n & 1) || n == 1) {
    return false;
  }
  auto powmod64 = [](ull x, ull y, ull mod) -> ull {
    ull ret = 1;
    while(y) {
      if(y & 1) {
        ret = (__uint128_t)ret * x % mod;
      }
      x = (__uint128_t)x * x % mod;
      y >>= 1;
    }
    return ret;
  };
  const ull primes[12] {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37};
  int r = 0;
  ull d = n - 1;
  while(!(d & 1)) {
    d >>= 1;
    ++r;
  }
  for(const ull p: primes) {
    if(p > n - 2) {
      break;
    }
    ull x = powmod64(p, d, n);
    if(x == 1 || x == n - 1) {
      continue;
    }
    bool composite = true;
    for(int i = 0; i < r - 1; ++i) {
      x = powmod64(x, 2, n);
      if(x == n - 1) {
        composite = false;
        break;
      }
    }
    if(composite) {
      return false;
    }
  }
  return true;
}

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int n;
  cin >> n;
  while(n--) {
    ull x;
    cin >> x;
    cout << x << ' ' << isPrime(x) << '\n';
  }
}
0