|
| 1 | +""" |
| 2 | +Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten |
| 3 | +pentagonal numbers are: |
| 4 | +1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... |
| 5 | +It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, |
| 6 | +70 − 22 = 48, is not pentagonal. |
| 7 | +
|
| 8 | +Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference |
| 9 | +are pentagonal and D = |Pk − Pj| is minimised; what is the value of D? |
| 10 | +""" |
| 11 | + |
| 12 | + |
| 13 | +def is_pentagonal(n: int) -> bool: |
| 14 | + """ |
| 15 | + Returns True if n is pentagonal, False otherwise. |
| 16 | + >>> is_pentagonal(330) |
| 17 | + True |
| 18 | + >>> is_pentagonal(7683) |
| 19 | + False |
| 20 | + >>> is_pentagonal(2380) |
| 21 | + True |
| 22 | + """ |
| 23 | + root = (1 + 24 * n) ** 0.5 |
| 24 | + return ((1 + root) / 6) % 1 == 0 |
| 25 | + |
| 26 | + |
| 27 | +def compute_num(limit: int = 5000) -> int: |
| 28 | + """ |
| 29 | + Returns the minimum difference of two pentagonal numbers P1 and P2 such that |
| 30 | + P1 + P2 is pentagonal and P2 - P1 is pentagonal. |
| 31 | + >>> compute_num(5000) |
| 32 | + 5482660 |
| 33 | + """ |
| 34 | + pentagonal_nums = [(i * (3 * i - 1)) // 2 for i in range(1, limit)] |
| 35 | + for i, pentagonal_i in enumerate(pentagonal_nums): |
| 36 | + for j in range(i, len(pentagonal_nums)): |
| 37 | + pentagonal_j = pentagonal_nums[j] |
| 38 | + a = pentagonal_i + pentagonal_j |
| 39 | + b = pentagonal_j - pentagonal_i |
| 40 | + if is_pentagonal(a) and is_pentagonal(b): |
| 41 | + return b |
| 42 | + |
| 43 | + |
| 44 | +if __name__ == "__main__": |
| 45 | + print(f"{compute_num() = }") |
0 commit comments