結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー simansiman
提出日時 2020-01-14 18:29:48
言語 Ruby
(3.2.2)
結果
AC  
実行時間 5,272 ms / 9,973 ms
コード長 814 bytes
コンパイル時間 113 ms
コンパイル使用メモリ 11,560 KB
実行使用メモリ 15,276 KB
最終ジャッジ日時 2023-08-10 16:13:55
合計ジャッジ時間 14,290 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 80 ms
15,044 KB
testcase_01 AC 77 ms
15,016 KB
testcase_02 AC 77 ms
15,136 KB
testcase_03 AC 81 ms
15,092 KB
testcase_04 AC 2,816 ms
15,260 KB
testcase_05 AC 2,632 ms
15,264 KB
testcase_06 AC 735 ms
15,140 KB
testcase_07 AC 718 ms
15,204 KB
testcase_08 AC 714 ms
15,276 KB
testcase_09 AC 5,272 ms
15,264 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

def modular_exponentiation(base, n, mod)
  res = 1

  while n > 0
    if n[0] == 1
      res = (res * base) % mod
    end

    base = (base ** 2) % mod
    n >>= 1
  end

  res
end

def witness(a, n)
  v = n - 1
  t = 0

  while v % 2 == 0
    t += 1
    v /= 2
  end

  u = n / (2 ** t)

  x = modular_exponentiation(a, u, n)

  t.times do
    bx = x
    x = (x ** 2) % n

    if x == 1 && bx != 1 && bx != n - 1
      return true
    end
  end

  return true if x != 1

  false
end

def miller_rabin(n, s = 10)
  return false if n <= 1
  return true if n == 2
  return false if n.even?

  s.times do
    a = rand(n - 1) + 1

    return false if witness(a, n)
  end

  true
end

N = gets.to_i

N.times do
  x = gets.to_i

  if miller_rabin(x)
    puts [x, 1].join(' ')
  else
    puts [x, 0].join(' ')
  end
end

0