forked from pratyushmp/code_opensource_2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprime_number_checker.py
More file actions
38 lines (27 loc) · 806 Bytes
/
Copy pathprime_number_checker.py
File metadata and controls
38 lines (27 loc) · 806 Bytes
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
import re
import sys
from math import ceil, sqrt
def is_prime(n: int) -> bool:
"""Returns True iff n is prime."""
if n == 2:
return True
elif n < 2 or n % 2 == 0:
return False
limit = ceil(sqrt(n))
for factor in range(3, limit + 1, 2):
if n % factor == 0:
return False
return True
def main():
while True:
num = input('Enter a number (or q to quit): ')
if num.lower() in ['q', 'quit']:
print('Bye!')
sys.exit(0)
if not re.match(r'^[-]?\d+$', num):
print(f"'{num}' is not a valid number")
sys.exit(1)
primeness = is_prime(int(num))
print(f"{num} is {'' if primeness else 'NOT '} prime")
if __name__ == '__main__':
main()