結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー かりあげクンかりあげクン
提出日時 2020-08-26 12:51:49
言語 Nim
(2.0.2)
結果
RE  
実行時間 -
コード長 1,679 bytes
コンパイル時間 3,249 ms
コンパイル使用メモリ 65,664 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-29 14:08:31
合計ジャッジ時間 3,810 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

import sequtils,strutils,math

proc powMod*(x,n:int,modulo:int = 0): int =
  proc mul(x,n,modulo:int):int =
    if n == 0: return 0
    if n == 1: return x
    result = mul(x,n div 2,modulo) mod modulo
    result = (result * 2) mod modulo
    result = (result + x * (n mod 2 == 1).int) mod modulo
  if n == 1: return x
  let
    pow_2 = powMod(x,n div 2,modulo)
    odd = if n mod 2 == 1: x else: 1
  if modulo > 0:
    const maybig = int.high.float.sqrt.int div 2
    if pow_2 > maybig or odd > maybig:
      result = mul(pow_2,pow_2,modulo)
      result = mul(result,odd,modulo)
    else:
      result = (pow_2 * pow_2) mod modulo
      result = (result * odd) mod modulo
  else:
    return pow_2 * pow_2 * odd
proc millerRabin*(n:int):bool =
  proc ctz(n:int):int{.importC: "__builtin_ctzll", noDecl .}
  proc power(x,n:int,modulo:int = 0): int =
    if n == 0: return 1
    if n == 1: return x
    let pow_2 = power(x,n div 2,modulo)
    result = pow_2 * pow_2 * (if n mod 2 == 1: x else: 1)
    if modulo > 0: result = result mod modulo
  if n <= 1 : return false
  if n == 2 or n == 3 or n == 5: return true
  if n mod 2 == 0: return false
  let
    s = ctz(n - 1)
    d = (n - 1) div (1 shl s)
  var a_list = @[2, 7, 61]
  if n >= 4_759_123_141 and n < 341_550_071_728_321:
    a_list = @[2, 3, 5, 7, 11, 13, 17, 1009]
  if n in a_list : return true
  for a in a_list:
    if powMod(a,d,n) == 1 : continue
    let notPrime = toSeq(0..<s).allIt(powMod(a,d*(1 shl it),n) != n-1)
    if notPrime : return false
  return true

var N = stdin.readLine.parseInt
for i in 0..<N:
  var z = stdin.readLine.parseInt
  if millerRabin(z): 
    echo $z & " 1"
  else:
    echo $z & " 0"
0