Neterukun's Library

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub Neterukun1993/Library

:heavy_check_mark: 確率的素数判定 (ミラー・ラビン素数判定法)
(NumberTheory/Prime/miller_rabin.py)

概要

確率的素数判定を行うアルゴリズム。$n < 2^{64}$ の範囲では決定的に素数判定できるよう実装している。

ミラー・ラビン素数判定法の定理

奇素数 $p = 2^s \cdot d + 1$ ($d$ は奇数) に対して、以下のいずれかが任意の整数 $a$ ($0 \lt a \lt p$) について成り立つ。

ミラー・ラビン素数判定法の定理の対偶

奇数 $n = 2^s \cdot d + 1$ ($d$ は奇数) に対して、以下のすべて満たす整数 $a$ が存在するならば、$n$ は合成数である。

ミラー・ラビン素数判定法では、この対偶を用いて確率的素数判定を行う。小さい整数の範囲では決定的に素数判定できる。例えば、$a = 2, 325, 9375, 28178, 450775, 9780504, 1795265022$ を用いることで、$n < 2^{64}$ の範囲では決定的になる (http://miller-rabin.appspot.com)。

使い方

miller_rabin(n: int) -> bool
n の確率的素数判定結果 (True: 素数である、False: 素数ではない) を返す。n が $2^{64}$ までの範囲では決定的である。計算量 $O(\log n)$

Verified with

Code

def miller_rabin(n):
    if n == 2:
        return True
    if n == 1 or n % 2 == 0:
        return False

    s = 0
    d = n - 1
    while d & 1 == 0:
        s += 1
        d >>= 1
    for a in (2, 325, 9375, 28178, 450775, 9780504, 1795265022):
        if n <= a:
            break
        x = pow(a, d, n)
        if x == 1:
            continue
        for _ in range(s):
            if x == n - 1:
                break
            x = x * x % n
        else:
            return False
    return True
Traceback (most recent call last):
  File "/opt/hostedtoolcache/Python/3.12.4/x64/lib/python3.12/site-packages/onlinejudge_verify/documentation/build.py", line 71, in _render_source_code_stat
    bundled_code = language.bundle(stat.path, basedir=basedir, options={'include_paths': [basedir]}).decode()
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/hostedtoolcache/Python/3.12.4/x64/lib/python3.12/site-packages/onlinejudge_verify/languages/python.py", line 96, in bundle
    raise NotImplementedError
NotImplementedError
Back to top page