|
| 1 | +""" |
| 2 | +Project Euler Problem 38 |
| 3 | +https://projecteuler.net/problem=38 |
| 4 | +
|
| 5 | +Take the number 192 and multiply it by each of 1, 2, and 3: |
| 6 | +
|
| 7 | +192 × 1 = 192 |
| 8 | +192 × 2 = 384 |
| 9 | +192 × 3 = 576 |
| 10 | +
|
| 11 | +By concatenating each product we get the 1 to 9 pandigital, 192384576. We will |
| 12 | +call 192384576 the concatenated product of 192 and (1,2,3) |
| 13 | +
|
| 14 | +The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, |
| 15 | +giving the pandigital, 918273645, which is the concatenated product of 9 and |
| 16 | +(1,2,3,4,5). |
| 17 | +
|
| 18 | +What is the largest 1 to 9 pandigital 9-digit number that can be formed as the |
| 19 | +concatenated product of an integer with (1,2, ... , n) where n > 1? |
| 20 | +""" |
| 21 | + |
| 22 | + |
| 23 | +def solution() -> int: |
| 24 | + """ |
| 25 | + Calculates and returns the largest 1-9 pandigital 9-digit number as product of |
| 26 | + integer set n>1. |
| 27 | +
|
| 28 | + Answer: |
| 29 | + >>> solution() |
| 30 | + 932718654 |
| 31 | +
|
| 32 | + Assumptions: |
| 33 | + 1. Since n>1, we'll concatenate the fixed number at least twice. We only need |
| 34 | + 9 digits, so 2x5=10 would exceed this safely. Thus target number is 4 |
| 35 | + digits or less. |
| 36 | + 2. We know at least one 9-digit pandigital starts with 9 as per the example, |
| 37 | + so can short circuit search based on that. |
| 38 | + 3. We can start with 90, the next 9-start number following 9 (already calculated) |
| 39 | + """ |
| 40 | + |
| 41 | + largest_pandigital = 918273645 |
| 42 | + |
| 43 | + for fixed_num in range(90, 10000): # assumption 1 and 3 |
| 44 | + if not str(fixed_num).startswith("9"): # assumption 2 |
| 45 | + continue |
| 46 | + |
| 47 | + pan = fixed_num |
| 48 | + i = 2 |
| 49 | + while len(str(pan)) < 9: |
| 50 | + pan = int(str(pan) + str(fixed_num * i)) |
| 51 | + |
| 52 | + if is_pandigital(pan) and pan > largest_pandigital: |
| 53 | + largest_pandigital = pan |
| 54 | + |
| 55 | + return largest_pandigital |
| 56 | + |
| 57 | + |
| 58 | +def is_pandigital(num: int) -> bool: |
| 59 | + """ |
| 60 | + Validates that a number is 9-digit pandigital. |
| 61 | + i.e. contains all numbers 1-9 without zero. |
| 62 | +
|
| 63 | + Examples: |
| 64 | + >>> is_pandigital(123456789) |
| 65 | + True |
| 66 | + >>> is_pandigital(987654321) |
| 67 | + True |
| 68 | + >>> is_pandigital(1234567890) |
| 69 | + False |
| 70 | + >>> is_pandigital(111111111) |
| 71 | + False |
| 72 | + """ |
| 73 | + |
| 74 | + # check that only digits 1-9 are present with no duplicates |
| 75 | + numberset = set(str(num)) |
| 76 | + return len(numberset) == 9 and "0" not in numberset |
| 77 | + |
| 78 | + |
| 79 | +if __name__ == "__main__": |
| 80 | + |
| 81 | + print(solution()) |
0 commit comments