|
| 1 | +""" |
| 2 | +Project Euler 62 |
| 3 | +https://projecteuler.net/problem=62 |
| 4 | +
|
| 5 | +The cube, 41063625 (345^3), can be permuted to produce two other cubes: |
| 6 | +56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube |
| 7 | +which has exactly three permutations of its digits which are also cube. |
| 8 | +
|
| 9 | +Find the smallest cube for which exactly five permutations of its digits are |
| 10 | +cube. |
| 11 | +""" |
| 12 | + |
| 13 | +from collections import defaultdict |
| 14 | + |
| 15 | + |
| 16 | +def solution(max_base: int = 5) -> int: |
| 17 | + """ |
| 18 | + Iterate through every possible cube and sort the cube's digits in |
| 19 | + ascending order. Sorting maintains an ordering of the digits that allows |
| 20 | + you to compare permutations. Store each sorted sequence of digits in a |
| 21 | + dictionary, whose key is the sequence of digits and value is a list of |
| 22 | + numbers that are the base of the cube. |
| 23 | +
|
| 24 | + Once you find 5 numbers that produce the same sequence of digits, return |
| 25 | + the smallest one, which is at index 0 since we insert each base number in |
| 26 | + ascending order. |
| 27 | +
|
| 28 | + >>> solution(2) |
| 29 | + 125 |
| 30 | + >>> solution(3) |
| 31 | + 41063625 |
| 32 | + """ |
| 33 | + freqs = defaultdict(list) |
| 34 | + num = 0 |
| 35 | + |
| 36 | + while True: |
| 37 | + digits = get_digits(num) |
| 38 | + freqs[digits].append(num) |
| 39 | + |
| 40 | + if len(freqs[digits]) == max_base: |
| 41 | + base = freqs[digits][0] ** 3 |
| 42 | + return base |
| 43 | + |
| 44 | + num += 1 |
| 45 | + |
| 46 | + |
| 47 | +def get_digits(num: int) -> str: |
| 48 | + """ |
| 49 | + Computes the sorted sequence of digits of the cube of num. |
| 50 | +
|
| 51 | + >>> get_digits(3) |
| 52 | + '27' |
| 53 | + >>> get_digits(99) |
| 54 | + '027999' |
| 55 | + >>> get_digits(123) |
| 56 | + '0166788' |
| 57 | + """ |
| 58 | + return "".join(sorted(list(str(num ** 3)))) |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == "__main__": |
| 62 | + print(f"{solution() = }") |
0 commit comments