|
| 1 | +""" |
| 2 | +The number, 1406357289, is a 0 to 9 pandigital number because it is made up of |
| 3 | +each of the digits 0 to 9 in some order, but it also has a rather interesting |
| 4 | +sub-string divisibility property. |
| 5 | +
|
| 6 | +Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note |
| 7 | +the following: |
| 8 | +
|
| 9 | +d2d3d4=406 is divisible by 2 |
| 10 | +d3d4d5=063 is divisible by 3 |
| 11 | +d4d5d6=635 is divisible by 5 |
| 12 | +d5d6d7=357 is divisible by 7 |
| 13 | +d6d7d8=572 is divisible by 11 |
| 14 | +d7d8d9=728 is divisible by 13 |
| 15 | +d8d9d10=289 is divisible by 17 |
| 16 | +Find the sum of all 0 to 9 pandigital numbers with this property. |
| 17 | +""" |
| 18 | + |
| 19 | + |
| 20 | +from itertools import permutations |
| 21 | + |
| 22 | + |
| 23 | +def is_substring_divisible(num: tuple) -> bool: |
| 24 | + """ |
| 25 | + Returns True if the pandigital number passes |
| 26 | + all the divisibility tests. |
| 27 | + >>> is_substring_divisible((0, 1, 2, 4, 6, 5, 7, 3, 8, 9)) |
| 28 | + False |
| 29 | + >>> is_substring_divisible((5, 1, 2, 4, 6, 0, 7, 8, 3, 9)) |
| 30 | + False |
| 31 | + >>> is_substring_divisible((1, 4, 0, 6, 3, 5, 7, 2, 8, 9)) |
| 32 | + True |
| 33 | + """ |
| 34 | + tests = [2, 3, 5, 7, 11, 13, 17] |
| 35 | + for i, test in enumerate(tests): |
| 36 | + if (num[i + 1] * 100 + num[i + 2] * 10 + num[i + 3]) % test != 0: |
| 37 | + return False |
| 38 | + return True |
| 39 | + |
| 40 | + |
| 41 | +def compute_sum(n: int = 10) -> int: |
| 42 | + """ |
| 43 | + Returns the sum of all pandigital numbers which pass the |
| 44 | + divisiility tests. |
| 45 | + >>> compute_sum(10) |
| 46 | + 16695334890 |
| 47 | + """ |
| 48 | + list_nums = [ |
| 49 | + int("".join(map(str, num))) |
| 50 | + for num in permutations(range(n)) |
| 51 | + if is_substring_divisible(num) |
| 52 | + ] |
| 53 | + |
| 54 | + return sum(list_nums) |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == "__main__": |
| 58 | + print(f"{compute_sum(10) = }") |
0 commit comments