結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー hari64hari64
提出日時 2021-07-27 22:40:02
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 464 ms / 9,973 ms
コード長 1,029 bytes
コンパイル時間 494 ms
コンパイル使用メモリ 86,972 KB
実行使用メモリ 78,792 KB
最終ジャッジ日時 2023-08-10 16:31:21
合計ジャッジ時間 3,461 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 70 ms
71,280 KB
testcase_01 AC 71 ms
71,280 KB
testcase_02 AC 73 ms
71,344 KB
testcase_03 AC 71 ms
71,332 KB
testcase_04 AC 368 ms
78,700 KB
testcase_05 AC 332 ms
78,272 KB
testcase_06 AC 225 ms
78,124 KB
testcase_07 AC 224 ms
78,792 KB
testcase_08 AC 220 ms
78,444 KB
testcase_09 AC 464 ms
78,372 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

def is_prime(n: int) -> bool:  # ミラー–ラビン素数判定法
    # https://qiita.com/srtk86/items/609737d50c9ef5f5dc59
    # http://miller-rabin.appspot.com/
    assert isinstance(n, int) and 0 < n
    if n == 2:
        return True
    if n == 1 or n & 1 == 0:
        return False
    d = (n - 1) >> 1
    while d & 1 == 0:
        d >>= 1  # n-1=(2**s)*d (dは奇数)
    L = [a for a in (2, 7, 61, 325, 9375, 28178, 450775,
                     9780504, 1795265022) if a < n]
    if n >= 2**64:
        from random import randint
        L += [randint(1, n-1) for _ in range(20)]
    for a in L:  # nが素数ならばa^d≡1 (mod p) もしくは
        t = d  # a^((2^r)*d)≡-1 (mod p) が成立すべき
        y = pow(a, t, n)
        while t != n - 1 and y != 1 and y != n - 1:
            y = (y * y) % n
            t <<= 1
        if y != n - 1 and t & 1 == 0:
            return False
    else:
        return True


n = int(input())
for _ in range(n):
    x = int(input())
    print(x, int(is_prime(x)))
0