結果

問題 No.308 素数は通れません
ユーザー wasd314
提出日時 2025-08-23 17:24:01
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
AC  
実行時間 28 ms / 1,000 ms
コード長 2,015 bytes
コンパイル時間 199 ms
コンパイル使用メモリ 12,288 KB
実行使用メモリ 10,624 KB
最終ジャッジ日時 2025-08-23 17:24:07
合計ジャッジ時間 5,908 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 107
権限があれば一括ダウンロードができます

ソースコード

diff #

def test_miller_rabin(n: int, bases: list):
    nn = n - 1
    e = (nn & -nn).bit_length() - 1
    o = n >> e
    assert n == (o << e | 1)
    for b in bases:
        x = pow(b, o, n)
        if x == 1:
            continue
        for _ in range(e):
            y = pow(x, 2, n)
            if y == 1:
                if x == n - 1:
                    break
                else:
                    # nontrivial sqrt(1) found
                    return False
            x = y
        else:
            return False
    return True

def is_prime(n: int):
    if n < 2:
        return False
    for p in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]:
        if n == p:
            return True
        if n % p == 0:
            return False
    if n < 41**2:
        return True
    if n < 2047:
        return test_miller_rabin(n, [2])
    if n < 90_80191:
        return test_miller_rabin(n, [31, 73])
    if n < 47591_23141:
        return test_miller_rabin(n, [2, 7, 61])
    if n < 112_20046_69633:
        return test_miller_rabin(n, [2, 13, 23, 16_62803])
    if n < 3_77057_95821_54547:
        return test_miller_rabin(n, [2, 8_80937, 25_70940, 6103_86380, 41307_85767])
    if n < 2**64:
        test_miller_rabin(n, [2, 325, 9375, 28178, 450775, 9780504, 17952_65022])
    if n < 18446744073709551616:
        return test_miller_rabin(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
    if n < 318665857834031151167461:
        return test_miller_rabin(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37])
    if n < 3317044064679887385961981:
        return test_miller_rabin(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41])
    assert False

def solve(n: int):
    d = {4: 3, 6: 5, 8: 7, 9: 7, 10: 7, 12: 11, 14: 13, 15: 7, 16: 7, 20: 19, 21: 19, 22: 7, 24: 23, 25: 23}
    if n in d:
        return d[n]
    if n % 8 == 1 and is_prime(n - 8):
        return 14
    return 8

case_t = 1
# case_t = int(input())
for _ in [None] * case_t:
    n = int(input())
    ans = solve(n)
    print(ans)

0