372 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
Sample Run of the Rabin Miller Module
If you run the interactive shell, you can import the rabinMiller.py module and call the functions
in it. Try typing the following into the interactive shell:
import rabinMiller
rabinMiller.generateLargePrime()
1228811683422110410305236835154432390074842906007015553694882717483780547440094
6375131251147129101194573241337844666680914050203700367321105215349360768161999
0563076859566835016382556518967124921538212397036345815983641146000671635019637
218348455544435908428400192565849620509600312468757953899553441648428119
rabinMiller.isPrime(45943208739848451)
False
rabinMiller.isPrime(13)
True
How the Program Works..........................................................................................................................................
rabinMiller.py
Primality Testing with the Rabin-Miller Algorithm
http://inventwithpython.com/hacking (BSD Licensed)
- import random
The Rabin-Miller algorithm uses random numbers, so we import the random module on line 4.
The Rabin-Miller Primality Algorithm
rabinMiller.py
- def rabinMiller(num):
Returns True if num is a prime number.
- s = num - 1
- t = 0
- while s % 2 == 0:
keep halving s while it is even (and use t
to count how many times we halve s)
- s = s // 2
- t += 1
- for trials in range(5): # try to falsify num's primality 5 times
- a = random.randrange(2, num - 1)
- v = pow(a, s, num)
- if v != 1: # this test does not apply if v is 1.