-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathA_06_c_MillerRabin.py
69 lines (54 loc) · 1.31 KB
/
A_06_c_MillerRabin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Author: Devashish Roy, Roll No: 2024PGCSIS08
# Assignment No: 06
# Implementation of Algorithms for Primality Testing
# a) Division Algorithms
# b) Fermat’s Theorem
# c) Miller-Rabin algorithm
# Miller-Rabin algorithm
import random
def negative_mod(x, n):
reminder = x % n
return reminder-n
def step1(n):
n = n-1
k = 1
while (n % pow(2, k) != 0):
k += 1
# print("k:", k, "m:", n//pow(2, k))
return k, n//pow(2, k)
def step2(n):
# return random.randint(1, n-1)
return 2
def step3(n, m, a, k):
T = pow(a, m) % n
T_negative = negative_mod(pow(a, m), n)
if T == 1 or T_negative == -1:
return True
for i in range(0, k):
x = T
T = pow(x, 2) % n
T_negative = negative_mod(pow(x, 2), n)
if T == 1:
return False
if T_negative == -1:
return True
return False
def miller_rabin(n):
k, m = step1(n)
a = step2(n)
x = step3(n, m, a, k)
return x
if __name__ == "__main__":
flag = True
while flag:
n = input("Input n: ")
try:
n = int(n)
flag = False
except:
print("Error: Please input a number.")
x = miller_rabin(n)
if x :
print("Prime")
else :
print("Composite")