码迷,mamicode.com
首页 > 编程语言 > 详细

Miller-Rabin素性测试(Python实现)

时间:2020-01-18 16:10:39      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:fas   pytho   dom   __name__   random   continue   prim   python实现   python   

import random

def fast_power(base, power, n):
    result = 1
    tmp = base
    while power > 0:
        if power&1 == 1:
            result = (result * tmp) % n
        tmp = (tmp * tmp) % n 
        power = power>>1
    return result

def Miller_Rabin(n, iter_num):
    # 2 is prime
    if n == 2:
        return True
    # if n is even or less than 2, then n is not a prime
    if n&1 == 0 or n<2:
        return False
    # n-1 = (2^s)m
    m,s = n - 1,0
    while m&1==0:
        m = m>>1
        s += 1
    # M-R test
    for _ in range(iter_num):
        b = fast_power(random.randint(2,n-1), m, n)
        if b==1 or b== n-1:
            continue
        for __ in range(s-1):
            b = fast_power(b, 2, n)
            if b == n-1:
                break
        else:
            return False
    return True
    

if __name__ == "__main__":
    # example
    print(Miller_Rabin(49139, 10))
    print(Miller_Rabin(561, 10))

Miller-Rabin素性测试(Python实现)

标签:fas   pytho   dom   __name__   random   continue   prim   python实现   python   

原文地址:https://www.cnblogs.com/philolif/p/prime-test.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!