Miller-Rabin 素性檢測
阿新 • • 發佈:2021-07-07
Miller-Rabin 素性檢測
演算法介紹
根據費馬小定理,設 p 是素數,a 為整數,且 gcd(a,p) = 1,則 ap-1 mod p = 1,以及二次探測定理:如果 p 是一個素數,且 0 < x < p,且方程 x2 = 1 (mod p) 成立,那麼 x = 1 或 x = p - 1。Miller-Rabin 素性檢測演算法是基於以上兩個定理的隨機化演算法,用於判斷一個數是合數還是素數,判斷 n 是否為素數的具體步驟如下:
- 令 n - 1 = 2k q,其中 k > 0,q 為奇數,隨機選取整數 a,1 < a < n - 1
- 若 aq mod n = 1,則 n 有可能是素數
- 取整數 j,0 ≤ j < k,若存在 \(a^{2^j}\)
由以上分析可知,素數一定能通過測試,不通過測試的必為合數,通過測試的很可能是素數,這就是 Miller-Rabin 素性檢測演算法
演算法流程圖
具體程式碼(python)
import random def _MillerRabinTest(n: int, t: int): """ :param n: 待檢測整數 :param t: 檢測輪數 :return: 是否通過檢測 """ if n < 3 or (n & 1 == 0): return n == 2 k, q = 0, n - 1 # 計算 q 和 k while not q & 1: q = q // 2 k = k + 1 tested = [] for _ in range(t): composite = True a = random.randint(2, n - 2) # 隨機生成2~n-2之間的整數 while a in tested: a = random.randint(2, n - 2) tested.append(a) r = pow(a, q, n) # 呼叫快速模冪演算法,計算 a^q mod n if r == 1 or r == n - 1: composite = False else: # 計算 a^(q·2^j) mod n for j in range(1, k): r = (r * r) % n if r == n - 1: composite = False break if composite: return False return True
用途
Miller-Rabin 演算法用於大素數的判斷與生成,Miller-Rabin 一次檢測誤判的概率大約為 0.25,經過多次檢測後依舊誤判的概率很小
判斷素數
由於 Miller-Rabin 演算法的時間複雜度較高,所以在判斷素數時儘可能不要用 Miller-Rabin,先通過其它方式檢測,最後再採用 Miller-Rabin
一個常見的方法是儲存一個較大的素數表,若待檢測的數不是表中素數的倍數,再採用 Miller-Rabin 演算法
下面給出了判斷素數的示例程式碼,由於篇幅原因,素數表只使用了 103 以內的素數,實際上可以增大到 106
import random def _MillerRabinTest(n: int, t: int): ... def is_prime(n: int): """ :return: 是素數(True) 不是素數(False) """ if n < 3 or (n & 1 == 0): return n == 2 for p in _sieve_base: if n == p: return True if n % p == 0: return False return _MillerRabinTest(n, 100) _sieve_base = ( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 )
生成素數
下面給出了生成指定位元大小素數的樣例
import random
def is_prime(n: int):
...
def get_prime(bits: int):
"""
:param bits: 素數的位數
:return: bits 位的素數
"""
if bits < 2:
return None
bound_l, bound_r = 1 << (bits - 1), 1 << bits
p = random.randint(bound_l, bound_r - 1)
while not is_prime(p):
p = random.randint(bound_l, bound_r - 1)
return p