Created
August 24, 2022 14:49
-
-
Save rhotav/4b8975c04127225a3a198b0a2490ff40 to your computer and use it in GitHub Desktop.
Miller-Rabin Primality Test Python Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python Version : 3.10.6 64-bit | |
def main(): | |
number = int(input("Insert an odd number: ")) | |
#step 1 - select a number in this range (n > 2) | |
if(number <= 2 and | |
number % 2 == 0): | |
print("Please insert an odd number in this range (n > 2) ") | |
return | |
#step 2 -- n - 1 = 2^k \times m | |
k = 0 | |
m = 0 | |
if ((number - 1) % 2 == 0): | |
k = (number - 1) // 2 | |
while (k % 2 == 0): | |
k = k // 2 | |
m = (number - 1) // k | |
print("k = {0}, m = {1}".format(k, m)) | |
else: | |
print("error") | |
return | |
#step 3 -- $b_i = 2^m (mod n) \mp 1 | |
# \mp = minusplus | |
# ** = ^ | |
b = (2 ** k) % number | |
while True: | |
if(b == 1): | |
print("{0} is prime".format(number)) | |
return | |
if(b == -1): | |
print("{0} is not prime".format(number)) | |
return | |
b = b ** 2 % number | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment