|
| 1 | +""" |
| 2 | +Project Euler 206 |
| 3 | +https://projecteuler.net/problem=206 |
| 4 | +
|
| 5 | +Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0, |
| 6 | +where each “_” is a single digit. |
| 7 | +""" |
| 8 | + |
| 9 | + |
| 10 | +def solution() -> int: |
| 11 | + """ |
| 12 | + Instead of computing every single permutation of that number and going |
| 13 | + through a 10^9 search space, we can narrow it down considerably. |
| 14 | +
|
| 15 | + If the square ends in a 0, then the square root must also end in a 0. Thus, |
| 16 | + the last missing digit must be 0 and the square root is a multiple of 10. |
| 17 | + We can narrow the search space down to the first 8 digits and multiply the |
| 18 | + result of that by 10 at the end. |
| 19 | +
|
| 20 | + Now the last digit is a 9, which can only happen if the square root ends |
| 21 | + in a 3 or 7. We can either start checking for the square root from |
| 22 | + 101010103, which is the closest square root of 10203040506070809 that ends |
| 23 | + in 3 or 7, or 138902663, the closest square root of 1929394959697989. The |
| 24 | + problem says there's only 1 answer, so starting at either point is fine, |
| 25 | + but the result happens to be much closer to the latter. |
| 26 | + """ |
| 27 | + num = 138902663 |
| 28 | + |
| 29 | + while not is_square_form(num * num): |
| 30 | + if num % 10 == 3: |
| 31 | + num -= 6 # (3 - 6) % 10 = 7 |
| 32 | + else: |
| 33 | + num -= 4 # (7 - 4) % 10 = 3 |
| 34 | + |
| 35 | + return num * 10 |
| 36 | + |
| 37 | + |
| 38 | +def is_square_form(num: int) -> bool: |
| 39 | + """ |
| 40 | + Determines if num is in the form 1_2_3_4_5_6_7_8_9 |
| 41 | +
|
| 42 | + >>> is_square_form(1) |
| 43 | + False |
| 44 | + >>> is_square_form(112233445566778899) |
| 45 | + True |
| 46 | + >>> is_square_form(123456789012345678) |
| 47 | + False |
| 48 | + """ |
| 49 | + digit = 9 |
| 50 | + |
| 51 | + while num > 0: |
| 52 | + if num % 10 != digit: |
| 53 | + return False |
| 54 | + num //= 100 |
| 55 | + digit -= 1 |
| 56 | + |
| 57 | + return True |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + print(solution()) |
0 commit comments