結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー pekempeypekempey
提出日時 2017-10-22 14:09:26
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
WA  
実行時間 -
コード長 1,394 bytes
コンパイル時間 807 ms
コンパイル使用メモリ 85,696 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-29 12:40:47
合計ジャッジ時間 5,263 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cassert>
#include <cstring>
#include <random>

using namespace std;

mt19937 mt(123456);

bool miller_rabin(unsigned long long n) {
  if (n <= 1) return false;
  if (n == 2) return true;

  unsigned long long s = n - 1;
  int e = 0;
  for (; s % 2 == 0; s /= 2) e++;
  // n-1 = s 2^e

  auto mul = [&](unsigned long long a, unsigned long long b, unsigned long long m) {
    unsigned long long r = 0;
    for (; b > 0; b >>= 1) {
      if (b & 1) {
        r += a;
        if (r >= m) r -= m;
      }
      a += a;
      if (a >= m) a -= m;
    }
    return r;
  };

  for (int ii = 0; ii < 5; ii++) {
    unsigned long long x = std::uniform_int_distribution<unsigned long long>(2, n - 1)(mt);
    unsigned long long r = 1;
    for (unsigned long long i = s; i > 0; i >>= 1) {
      if (i & 1) r = mul(r, x, n);
      x = mul(x, x, n);
    }
    if (r == 1 || r == n - 1) continue;
    for (int i = 0; i < e - 1; i++) {
      r = mul(r, r, n);
      if (r == n - 1) break;
    }
    if (r != n - 1) return false;
  }

  return true;
}

bool is_prime(long long n) {
  for (long long i = 2; i * i <= n; i++) {
    if (n % i == 0) return false;
  }
  return n != 1;
}

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

  while (n--) {
    long long x;
    scanf("%lld", &x);
    printf("%lld %d\n", x, miller_rabin(x));
  }
}
0