-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnearest-primes.py
87 lines (78 loc) · 2.11 KB
/
nearest-primes.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# This method finds the closest prime numbers to user's input
import time
a = float(input("Enter a natural number: "))
print()
if a <= 0 or (a - a // 1) != 0:
while a <= 0 or (a - a // 1) != 0:
a = float(input("Your input must be natural! "))
a = int(a)
n1 = a+1
n2 = a-1
p = None
start_time = time.time()
print("(!) Searching for nearest prime numbers...")
while not p:
i = 2
while i <= n1 ** 0.5:
d = n1 % i
if d == 0:
break
else:
i += 1
d = n1 % i
if d == 0 and n1 != 2:
p = False
n1 += 1
elif d != 0 or n1 <= 3:
p = True
break
p = None
while not p:
i = 2
while i <= n2 ** 0.5:
d = n2 % i
if d == 0:
break
else:
i += 1
d = n2 % i
if d == 0 and n2 != 2:
p = False
n2 -= 1
elif d != 0 or n2 <= 3:
p = True
if n2 == 1:
n2 = "NONE"
break
end_time = time.time()
elapsed_time = end_time - start_time
elapsed_time *= 1000
el_time = elapsed_time
if elapsed_time < 1000:
ms = int(elapsed_time // 1)
elapsed_time = str(ms) + " ms"
elif 1000 <= elapsed_time < 60000:
secs = int(elapsed_time // 1000)
ms = int(elapsed_time // 1 - 1000 * secs)
elapsed_time = str(secs) + " s " + str(ms) + " ms"
elif 60000 <= elapsed_time < 3600000:
mins = int(elapsed_time // 60000)
secs = int((int(elapsed_time // 1) - 60000 * mins) // 1000)
ms = int(((int(elapsed_time // 1) - 60000 * mins) - 1000 * secs) // 1)
elapsed_time = str(mins) + " m " + str(secs) + " s " + str(ms) + " ms"
else:
hrs = int(elapsed_time // 3600000)
mins = int(elapsed_time // 1) - 3600000 * hrs
s_mins = mins
mins = int(mins // 60000)
secs = s_mins - 60000 * mins
s_secs = secs
secs = int(secs // 1000)
ms = s_secs - 1000 * secs
elapsed_time = str(hrs) + " h " + str(mins) + " m " + str(secs) + " s " + str(ms) + " ms"
print()
print("[!] The nearest from above:", n1)
print("[!] The nearest from below:", n2)
if int(el_time // 1) != 0:
print()
print("(!) Elapsed time:", elapsed_time)