-
Notifications
You must be signed in to change notification settings - Fork 0
/
101.py
63 lines (45 loc) · 1.46 KB
/
101.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
"""
Problem:
Given an even number (greater than 2), return two prime numbers whose sum will be equal
to the given number.
A solution will always exist. See Goldbach’s conjecture.
Example:
numut: 4 Output: 2 + 2 = 4 If there are more than one solution possible, return the
lexicographically smaller solution.
If [a, b] is one solution with a <= b, and [c, d] is another solution with c <= d, then
[a, b] < [c, d]
if a < c or a==c and b < d.
"""
from typing import Tuple
def is_prime(num: int) -> bool:
# time complexity: O(log(n))
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def get_prime_sum(num: int) -> Tuple[int, int]:
if num > 2 and is_prime(num - 2):
return 2, num - 2
if num > 3 and is_prime(num - 3):
return 3, num - 3
# all prime numbers are of the form (6n + 1) or (6n - 1)
for i in range(6, num // 2, 6):
if is_prime(i - 1) and is_prime(num - i + 1):
return (i - 1), (num - i + 1)
elif is_prime(i + 1) and is_prime(num - i - 1):
return (i + 1), (num - i - 1)
if __name__ == "__main__":
num = 4
num_1, num_2 = get_prime_sum(num)
print(f"{num} = {num_1} + {num_2}")
num = 10
num_1, num_2 = get_prime_sum(num)
print(f"{num} = {num_1} + {num_2}")
num = 100
num_1, num_2 = get_prime_sum(num)
print(f"{num} = {num_1} + {num_2}")
"""
SPECS:
TIME COMPLEXITY: O(n x log(n))
SPACE COMPLEXITY: O(1)
"""