|
| 1 | +""" |
| 2 | +Project Euler Problem 77: https://projecteuler.net/problem=77 |
| 3 | +
|
| 4 | +It is possible to write ten as the sum of primes in exactly five different ways: |
| 5 | +
|
| 6 | +7 + 3 |
| 7 | +5 + 5 |
| 8 | +5 + 3 + 2 |
| 9 | +3 + 3 + 2 + 2 |
| 10 | +2 + 2 + 2 + 2 + 2 |
| 11 | +
|
| 12 | +What is the first value which can be written as the sum of primes in over |
| 13 | +five thousand different ways? |
| 14 | +""" |
| 15 | + |
| 16 | +from functools import lru_cache |
| 17 | +from math import ceil |
| 18 | +from typing import Optional, Set |
| 19 | + |
| 20 | +NUM_PRIMES = 100 |
| 21 | + |
| 22 | +primes = set(range(3, NUM_PRIMES, 2)) |
| 23 | +primes.add(2) |
| 24 | +prime: int |
| 25 | + |
| 26 | +for prime in range(3, ceil(NUM_PRIMES ** 0.5), 2): |
| 27 | + if prime not in primes: |
| 28 | + continue |
| 29 | + primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) |
| 30 | + |
| 31 | + |
| 32 | +@lru_cache(maxsize=100) |
| 33 | +def partition(number_to_partition: int) -> Set[int]: |
| 34 | + """ |
| 35 | + Return a set of integers corresponding to unique prime partitions of n. |
| 36 | + The unique prime partitions can be represented as unique prime decompositions, |
| 37 | + e.g. (7+3) <-> 7*3 = 12, (3+3+2+2) = 3*3*2*2 = 36 |
| 38 | + >>> partition(10) |
| 39 | + {32, 36, 21, 25, 30} |
| 40 | + >>> partition(15) |
| 41 | + {192, 160, 105, 44, 112, 243, 180, 150, 216, 26, 125, 126} |
| 42 | + >>> len(partition(20)) |
| 43 | + 26 |
| 44 | + """ |
| 45 | + if number_to_partition < 0: |
| 46 | + return set() |
| 47 | + elif number_to_partition == 0: |
| 48 | + return {1} |
| 49 | + |
| 50 | + ret: Set[int] = set() |
| 51 | + prime: int |
| 52 | + sub: int |
| 53 | + |
| 54 | + for prime in primes: |
| 55 | + if prime > number_to_partition: |
| 56 | + continue |
| 57 | + for sub in partition(number_to_partition - prime): |
| 58 | + ret.add(sub * prime) |
| 59 | + |
| 60 | + return ret |
| 61 | + |
| 62 | + |
| 63 | +def solution(number_unique_partitions: int = 5000) -> Optional[int]: |
| 64 | + """ |
| 65 | + Return the smallest integer that can be written as the sum of primes in over |
| 66 | + m unique ways. |
| 67 | + >>> solution(4) |
| 68 | + 10 |
| 69 | + >>> solution(500) |
| 70 | + 45 |
| 71 | + >>> solution(1000) |
| 72 | + 53 |
| 73 | + """ |
| 74 | + for number_to_partition in range(1, NUM_PRIMES): |
| 75 | + if len(partition(number_to_partition)) > number_unique_partitions: |
| 76 | + return number_to_partition |
| 77 | + return None |
| 78 | + |
| 79 | + |
| 80 | +if __name__ == "__main__": |
| 81 | + print(f"{solution() = }") |
0 commit comments