-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnolog.py
More file actions
48 lines (40 loc) · 1.19 KB
/
nolog.py
File metadata and controls
48 lines (40 loc) · 1.19 KB
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
import random
def miller_rabin(n, k=5):
""" Miller-Rabin primality test without logging.
n: the number to test for primality
k: number of iterations (more iterations = higher confidence)
"""
if n <= 1:
return False
if n <= 3:
return True # 2 and 3 are prime
if n % 2 == 0:
return False # Even number and not 2, so not prime
# Step 1: Write n-1 as 2^s * d
s, d = 0, n - 1
while d % 2 == 0:
d //= 2
s += 1
# Step 2: Test k random bases
for _ in range(k):
a = random.randint(2, n - 2)
# Compute a^d % n
x = pow(a, d, n)
if x == 1 or x == n - 1:
continue
# Square x repeatedly
for _ in range(s - 1):
x = pow(x, 2, n)
if x == n - 1:
break
else:
return False
return True
# Ask the user to input a number
user_input = int(input("Enter a number to check if it's prime: "))
iterations = int(input("Iterations: "))
result = miller_rabin(user_input, k=iterations)
if result:
print(f"{user_input} is probably prime.")
else:
print(f"{user_input} is not prime.")