結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー yuppe19 😺yuppe19 😺
提出日時 2017-10-20 13:17:06
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 398 ms / 9,973 ms
コード長 1,428 bytes
コンパイル時間 416 ms
コンパイル使用メモリ 60,580 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-08-10 15:47:25
合計ジャッジ時間 2,235 ms
ジャッジサーバーID
(参考情報)
judge12 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 1 ms
4,376 KB
testcase_04 AC 199 ms
4,376 KB
testcase_05 AC 197 ms
4,376 KB
testcase_06 AC 56 ms
4,376 KB
testcase_07 AC 55 ms
4,380 KB
testcase_08 AC 54 ms
4,380 KB
testcase_09 AC 398 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <algorithm>
#include <cassert>
using namespace std;
using u64 = unsigned long long;

u64 mod_mul(u64 a, u64 b, u64 m) {
  return __uint128_t(a) * b % m;
  // https://github.com/wizykowski/miller-rabin/blob/master/mulmod64.h
  //u64 res;
  //__asm__("mulq %2;"
  //        "divq %3;"
  //        : "=&d"(res), "+%a"(a)
  //        : "rm"(b), "rm"(m)
  //        : "cc");
  //return res;
}

u64 mod_pow(u64 x, u64 k, u64 m) {
  if(k == 0) { return 1; }
  if(k & 1) { return mod_mul(x, mod_pow(x, k-1, m), m); }
  return mod_pow(mod_mul(x, x, m), k>>1, m);
}

bool is_prime(u64 n) {
  if(n < 2) { return false; }
  for(u64&& p : {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31}) {
    if(n < p * p)  { return true; }
    if(n % p == 0) { return false; }
  }
  u64 s = 0, d = n-1;
  while(!(d & 1)) { ++s, d>>=1; }
  for(u64&& a : {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) {
    u64 x = mod_pow(a, d, n);
    if(x == 1 || x == n-1) { continue; }
    bool flag = false;
    for(u64 loop=1; loop<s; ++loop) {
      x = mod_mul(x, x, n);
      if(x == n-1) { flag = true; break; }
    }
    if(!flag) { return false; }
  }
  return true;
}

int main(void) {
  int n; scanf("%d", &n);
  assert(1 <= n && n <= 10000);
  for(int i=0; i<n; ++i) {
    long long x; scanf("%lld", &x);
    assert(1 <= x && x <= 9223372036854775807LL);
    bool flag = is_prime(x);
    printf("%lld %d\n", x, flag);
  }
  return 0;
}
0