Skip to content

Commit 4c59bf7

Browse files
committed
Readd Project Euler 206 solution for issue TheAlgorithms#2695, dupe of pull request TheAlgorithms#3042
1 parent a03b3f7 commit 4c59bf7

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

Diff for: project_euler/problem_206/__init__.py

Whitespace-only changes.

Diff for: project_euler/problem_206/sol1.py

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
"""
2+
Project Euler Problem 206: https://projecteuler.net/problem=206
3+
4+
Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0,
5+
where each “_” is a single digit.
6+
7+
-----
8+
9+
Instead of computing every single permutation of that number and going
10+
through a 10^9 search space, we can narrow it down considerably.
11+
12+
If the square ends in a 0, then the square root must also end in a 0. Thus,
13+
the last missing digit must be 0 and the square root is a multiple of 10.
14+
We can narrow the search space down to the first 8 digits and multiply the
15+
result of that by 10 at the end.
16+
17+
Now the last digit is a 9, which can only happen if the square root ends
18+
in a 3 or 7. From this point, we can try one of two different methods to find
19+
the answer:
20+
21+
1. Start at the lowest possible base number whose square would be in the
22+
format, and count up. The base we would start at is 101010103, whose square is
23+
the closest number to 10203040506070809. Alternate counting up by 4 and 6 so
24+
the last digit of the base is always a 3 or 7.
25+
26+
2. Start at the highest possible base number whose square would be in the
27+
format, and count down. That base would be 138902663, whose square is the
28+
closest number to 1929394959697989. Alternate counting down by 6 and 4 so the
29+
last digit of the base is always a 3 or 7.
30+
31+
The solution does option 2 because the answer happens to be much closer to the
32+
starting point.
33+
"""
34+
35+
36+
def is_square_form(num: int) -> bool:
37+
"""
38+
Determines if num is in the form 1_2_3_4_5_6_7_8_9
39+
40+
>>> is_square_form(1)
41+
False
42+
>>> is_square_form(112233445566778899)
43+
True
44+
>>> is_square_form(123456789012345678)
45+
False
46+
"""
47+
digit = 9
48+
49+
while num > 0:
50+
if num % 10 != digit:
51+
return False
52+
num //= 100
53+
digit -= 1
54+
55+
return True
56+
57+
58+
def solution() -> int:
59+
"""
60+
Returns the first integer whose square is of the form 1_2_3_4_5_6_7_8_9_0
61+
"""
62+
num = 138902663
63+
64+
while not is_square_form(num * num):
65+
if num % 10 == 3:
66+
num -= 6 # (3 - 6) % 10 = 7
67+
else:
68+
num -= 4 # (7 - 4) % 10 = 3
69+
70+
return num * 10
71+
72+
73+
if __name__ == "__main__":
74+
print(f"{solution() = }")

0 commit comments

Comments
 (0)