|
| 1 | +""" |
| 2 | +Project Euler Problem 142: https://projecteuler.net/problem=142 |
| 3 | +
|
| 4 | +Perfect Square Collection |
| 5 | +
|
| 6 | +Find the smallest x + y + z with integers x > y > z > 0 such that |
| 7 | +x + y, x - y, x + z, x - z, y + z, y - z are all perfect squares. |
| 8 | +
|
| 9 | +
|
| 10 | +Change the variables to a, b, c, so that 3 requirements are satisfied automatically: |
| 11 | +a^2 = y - z |
| 12 | +b^2 = x - y |
| 13 | +c^2 = z + x |
| 14 | +
|
| 15 | +and the rest of requirements for perfect squares are: |
| 16 | +z + y = c^2 - b^2 |
| 17 | +y + x = a^2 + c^2 |
| 18 | +x - z = a^2 + b^2 |
| 19 | +
|
| 20 | +Then iterate over a^2, b^2 and c^2 to check if the combination satisfies all |
| 21 | +3 requirements. |
| 22 | +
|
| 23 | +The total sum x + y + z = (a^2 - b^2 + 3c^2) / 2, so we break loop for c^2 if |
| 24 | +the sum is already bigger than found sum. |
| 25 | +
|
| 26 | +""" |
| 27 | + |
| 28 | + |
| 29 | +def solution(number_of_terms: int = 3) -> int | None: |
| 30 | + """ |
| 31 | +
|
| 32 | + Iterate over combinations of a, b, c and save min sum. |
| 33 | + In case only one term x = 1 is solution. |
| 34 | + In case of two terms, x = 5, y = 4 is the solution. |
| 35 | +
|
| 36 | + >>> solution(1) |
| 37 | + 1 |
| 38 | + >>> solution(2) |
| 39 | + 9 |
| 40 | + """ |
| 41 | + |
| 42 | + if number_of_terms == 1: |
| 43 | + return 1 |
| 44 | + if number_of_terms == 2: |
| 45 | + return 9 |
| 46 | + |
| 47 | + n_max = 2500 |
| 48 | + squares: list[int] = [] |
| 49 | + |
| 50 | + for a in range(n_max + 1): |
| 51 | + squares += [a * a] |
| 52 | + squares_set = set(squares) |
| 53 | + |
| 54 | + min_sum = None |
| 55 | + for a in range(1, len(squares)): |
| 56 | + a_sq = squares[a] |
| 57 | + for b in range(1, len(squares)): |
| 58 | + b_sq = squares[b] |
| 59 | + if a_sq + b_sq not in squares_set: |
| 60 | + continue |
| 61 | + for c in range(max(a, b) + 1, len(squares)): |
| 62 | + c_sq = squares[c] |
| 63 | + # break if x + y + z is already bigger than min_sum: |
| 64 | + if min_sum is not None and (a_sq - b_sq + 3 * c_sq) // 2 > min_sum: |
| 65 | + break |
| 66 | + if (c_sq - b_sq in squares_set) and (a_sq + c_sq in squares_set): |
| 67 | + x2, y2, z2 = ( |
| 68 | + a_sq + b_sq + c_sq, |
| 69 | + a_sq - b_sq + c_sq, |
| 70 | + c_sq - a_sq - b_sq, |
| 71 | + ) |
| 72 | + if z2 > 0 and x2 % 2 == 0 and y2 % 2 == 0 and z2 % 2 == 0: |
| 73 | + sum_ = (x2 + y2 + z2) // 2 |
| 74 | + min_sum = sum_ if min_sum is None else min(min_sum, sum_) |
| 75 | + |
| 76 | + return min_sum |
| 77 | + |
| 78 | + |
| 79 | +if __name__ == "__main__": |
| 80 | + print(f"{solution() = }") |
0 commit comments