結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー LanatusLanatus
提出日時 2022-12-13 04:27:30
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 542 ms / 9,973 ms
コード長 920 bytes
コンパイル時間 2,302 ms
コンパイル使用メモリ 194,764 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-24 16:23:08
合計ジャッジ時間 4,134 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

using ll = long long;
using ull = __int128_t;

ull modpow(ull a, ll n, ll m) {
  if (n == 0) return 1;
  if (n % 2) return a % m * modpow(a, n-1, m) % m;
  ull t = modpow(a, n/2, m);
  return t % m * t % m;
}

bool isPrime(ll x) {
  if (x == 2) return true;
  if (x == 1 || x % 2 == 0) return false;

  ll m = x-1;
  ll t = m;
  ll s = 0;

  while (t % 2 == 0) {
    t /= 2;
    ++s;
  }

  ll d = m / (1LL << s);
  
  for (ll a : {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) {
    if (a == x) return true;

    ull n = a;
    n = modpow(n, d, x);

    int r = 0;

    if (n == 1) continue;

    while (n != m) {
      n = modpow(n, 2, x);
      ++r;

      if (r == s) return false;
    }
  }

  return true;
}

int main(void) {
  int n;
  cin >> n;

  for (int i = 0; i < n; ++i) {
    ll x;
    cin >> x;

    cout << x << " " << isPrime(x) << endl;
  }

  return 0;
}
0