結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー こまるこまる
提出日時 2020-12-01 23:42:36
言語 PyPy3
(7.3.13)
結果
RE  
実行時間 -
コード長 2,100 bytes
コンパイル時間 290 ms
コンパイル使用メモリ 86,928 KB
実行使用メモリ 81,968 KB
最終ジャッジ日時 2023-08-11 23:29:40
合計ジャッジ時間 3,555 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 88 ms
72,308 KB
testcase_01 AC 90 ms
72,132 KB
testcase_02 AC 91 ms
71,856 KB
testcase_03 AC 89 ms
72,424 KB
testcase_04 RE -
testcase_05 AC 385 ms
79,968 KB
testcase_06 AC 249 ms
79,784 KB
testcase_07 AC 245 ms
79,320 KB
testcase_08 AC 249 ms
79,328 KB
testcase_09 AC 541 ms
80,148 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import os
import sys
import random


class Prime():
    def isPrimeMR(n):
        if n in {2, 3, 5, 7, 11, 13, 17}:
            return True
        d = n - 1
        d = d // (d & -d)
        L = (
            [2, 7, 61]
            if n < 1 << 32
            else [2, 3, 5, 7, 11, 13, 17]
            if n < 1 << 48
            else [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
        )
        for a in L:
            t = d
            y = pow(a, t, n)
            if y == 1:
                continue
            while y != n - 1:
                y = (y * y) % n
                if y == 1 or t == n - 1:
                    return False
                t <<= 1
        return True
    def miller_rabin(n, check):
        d = n - 1
        d = d // (d & -d)
        s = ((n - 1) // d).bit_length() - 1
        for a in check:
            if n <= a:
                return True
            a = pow(a, d, n)
            if a == 1:
                continue
            r = 1
            while a != n - 1:
                if r == s:
                    return False
                a = a * a % n
                r += 1
        return True

    def is_prime32(n):
        return Prime.miller_rabin(n, [2, 7, 61])

    def is_prime64(n):
        return Prime.miller_rabin(n, [2, 3, 5, 7, 325, 9375, 28178, 450775, 9780504, 1795265022])

    def is_prime(n):
        if n <= 1:
            return False
        if n <= 3:
            return True
        if n & 1 == 0:
            return False
        if n < 4759123141:
            return Prime.is_prime32(n)
        if n < 18446744073709551615:
            return Prime.is_prime64(n)
        d = (n - 1) >> 1
        while d & 1 == 0:
            d >>= 1
        for k in range(100):
            a = random.randint(1, n - 1)
            t = d
            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
        return True


for i in range(int(input())):
  x = int(input())
  print(x, int(Prime.isPrimeMR(x)))
0