forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprime_check.py
More file actions
43 lines (34 loc) · 805 Bytes
/
prime_check.py
File metadata and controls
43 lines (34 loc) · 805 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
39
40
41
42
43
"""
Primality Test
Check whether a given integer is prime using trial division with 6k +/- 1
optimization.
Reference: https://en.wikipedia.org/wiki/Primality_test
Complexity:
Time: O(sqrt(n))
Space: O(1)
"""
from __future__ import annotations
def prime_check(n: int) -> bool:
"""Check whether n is a prime number.
Args:
n: The integer to test.
Returns:
True if n is prime, False otherwise.
Examples:
>>> prime_check(7)
True
>>> prime_check(4)
False
"""
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
j = 5
while j * j <= n:
if n % j == 0 or n % (j + 2) == 0:
return False
j += 6
return True