|
| 1 | +""" |
| 2 | +It was proposed by Christian Goldbach that every odd composite number can be |
| 3 | +written as the sum of a prime and twice a square. |
| 4 | +
|
| 5 | +9 = 7 + 2 × 12 |
| 6 | +15 = 7 + 2 × 22 |
| 7 | +21 = 3 + 2 × 32 |
| 8 | +25 = 7 + 2 × 32 |
| 9 | +27 = 19 + 2 × 22 |
| 10 | +33 = 31 + 2 × 12 |
| 11 | +
|
| 12 | +It turns out that the conjecture was false. |
| 13 | +
|
| 14 | +What is the smallest odd composite that cannot be written as the sum of a |
| 15 | +prime and twice a square? |
| 16 | +""" |
| 17 | + |
| 18 | +from typing import List |
| 19 | + |
| 20 | +seive = [True] * 100001 |
| 21 | +i = 2 |
| 22 | +while i * i <= 100000: |
| 23 | + if seive[i]: |
| 24 | + for j in range(i * i, 100001, i): |
| 25 | + seive[j] = False |
| 26 | + i += 1 |
| 27 | + |
| 28 | + |
| 29 | +def is_prime(n: int) -> bool: |
| 30 | + """ |
| 31 | + Returns True if n is prime, |
| 32 | + False otherwise, for 2 <= n <= 100000 |
| 33 | + >>> is_prime(87) |
| 34 | + False |
| 35 | + >>> is_prime(23) |
| 36 | + True |
| 37 | + >>> is_prime(25363) |
| 38 | + False |
| 39 | + """ |
| 40 | + return seive[n] |
| 41 | + |
| 42 | + |
| 43 | +odd_composites = [num for num in range(3, len(seive), 2) if not is_prime(num)] |
| 44 | + |
| 45 | + |
| 46 | +def compute_nums(n: int) -> List[int]: |
| 47 | + """ |
| 48 | + Returns a list of first n odd composite numbers which do |
| 49 | + not follow the conjecture. |
| 50 | + >>> compute_nums(1) |
| 51 | + [5777] |
| 52 | + >>> compute_nums(2) |
| 53 | + [5777, 5993] |
| 54 | + >>> compute_nums(0) |
| 55 | + Traceback (most recent call last): |
| 56 | + ... |
| 57 | + ValueError: n must be >= 0 |
| 58 | + >>> compute_nums("a") |
| 59 | + Traceback (most recent call last): |
| 60 | + ... |
| 61 | + ValueError: n must be an integer |
| 62 | + >>> compute_nums(1.1) |
| 63 | + Traceback (most recent call last): |
| 64 | + ... |
| 65 | + ValueError: n must be an integer |
| 66 | +
|
| 67 | + """ |
| 68 | + if not isinstance(n, int): |
| 69 | + raise ValueError("n must be an integer") |
| 70 | + if n <= 0: |
| 71 | + raise ValueError("n must be >= 0") |
| 72 | + |
| 73 | + list_nums = [] |
| 74 | + for num in range(len(odd_composites)): |
| 75 | + i = 0 |
| 76 | + while 2 * i * i <= odd_composites[num]: |
| 77 | + rem = odd_composites[num] - 2 * i * i |
| 78 | + if is_prime(rem): |
| 79 | + break |
| 80 | + i += 1 |
| 81 | + else: |
| 82 | + list_nums.append(odd_composites[num]) |
| 83 | + if len(list_nums) == n: |
| 84 | + return list_nums |
| 85 | + |
| 86 | + |
| 87 | +if __name__ == "__main__": |
| 88 | + print(f"{compute_nums(1) = }") |
0 commit comments