Find the area of the grid which contains as close to two million rectangles as possible. >>> solution(20) 6 >>> solution(2000) 72 >>> solution(2000000000) 86595
(target: int = 2000000)
| 51 | |
| 52 | |
| 53 | def solution(target: int = 2000000) -> int: |
| 54 | """ |
| 55 | Find the area of the grid which contains as close to two million rectangles |
| 56 | as possible. |
| 57 | >>> solution(20) |
| 58 | 6 |
| 59 | >>> solution(2000) |
| 60 | 72 |
| 61 | >>> solution(2000000000) |
| 62 | 86595 |
| 63 | """ |
| 64 | triangle_numbers: list[int] = [0] |
| 65 | idx: int |
| 66 | |
| 67 | for idx in range(1, ceil(sqrt(target * 2) * 1.1)): |
| 68 | triangle_numbers.append(triangle_numbers[-1] + idx) |
| 69 | |
| 70 | # we want this to be as close as possible to target |
| 71 | best_product: int = 0 |
| 72 | # the area corresponding to the grid that gives the product closest to target |
| 73 | area: int = 0 |
| 74 | # an estimate of b, using the quadratic formula |
| 75 | b_estimate: float |
| 76 | # the largest integer less than b_estimate |
| 77 | b_floor: int |
| 78 | # the largest integer less than b_estimate |
| 79 | b_ceil: int |
| 80 | # the triangle number corresponding to b_floor |
| 81 | triangle_b_first_guess: int |
| 82 | # the triangle number corresponding to b_ceil |
| 83 | triangle_b_second_guess: int |
| 84 | |
| 85 | for idx_a, triangle_a in enumerate(triangle_numbers[1:], 1): |
| 86 | b_estimate = (-1 + sqrt(1 + 8 * target / triangle_a)) / 2 |
| 87 | b_floor = floor(b_estimate) |
| 88 | b_ceil = ceil(b_estimate) |
| 89 | triangle_b_first_guess = triangle_numbers[b_floor] |
| 90 | triangle_b_second_guess = triangle_numbers[b_ceil] |
| 91 | |
| 92 | if abs(target - triangle_b_first_guess * triangle_a) < abs( |
| 93 | target - best_product |
| 94 | ): |
| 95 | best_product = triangle_b_first_guess * triangle_a |
| 96 | area = idx_a * b_floor |
| 97 | |
| 98 | if abs(target - triangle_b_second_guess * triangle_a) < abs( |
| 99 | target - best_product |
| 100 | ): |
| 101 | best_product = triangle_b_second_guess * triangle_a |
| 102 | area = idx_a * b_ceil |
| 103 | |
| 104 | return area |
| 105 | |
| 106 | |
| 107 | if __name__ == "__main__": |