結果

問題 No.308 素数は通れません
ユーザー Min_25Min_25
提出日時 2015-12-01 03:38:29
言語 Python2
(2.7.18)
結果
AC  
実行時間 11 ms / 1,000 ms
コード長 928 bytes
コンパイル時間 1,017 ms
コンパイル使用メモリ 6,912 KB
実行使用メモリ 6,400 KB
最終ジャッジ日時 2024-11-27 18:07:46
合計ジャッジ時間 3,025 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 107
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys

def prob308():
  def witness(base, s, d, n):
    base = pow(base, d, n)
    if base == 1 or base == n - 1:
      return True
    for _ in range(s - 1):
      base = base * base % n
      if base == n - 1:
        return True
    return False

  def miller_rabin(n):
    if n <= 1:
      return False
    if n <= 3:
      return True

    d = n - 1
    s = d & -d
    s = s.bit_length() - 1
    d >>= s

    if n < 3317044064679887385961981:
      bases = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
    else:
      assert(0)

    for base in bases:
      if n % base == 0:
        return n == base
      if not witness(base, s, d, n):
        return False
    return True

  n = int(sys.stdin.readline())
  pre = [0, 0, 0, 0, 3, 0, 5, 0, 7, 7, 7, 0, 11, 0, 13, 7, 7, 0, 8, 0, 19, 19, 7, 0, 23, 23]
  ans = pre[n] if n < len(pre) else (8 if n % 8 != 1 or not miller_rabin(n - 8) else 14)
  print(ans)

prob308()
0