Skip to content

Commit ef0d092

Browse files
committed
Added solution for Project Euler problem 38. Fixes: #2695
1 parent c9500dc commit ef0d092

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

project_euler/problem_38/__init__.py

Whitespace-only changes.

project_euler/problem_38/sol1.py

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
"""
2+
Take the number 192 and multiply it by each of 1, 2, and 3:
3+
4+
192 × 1 = 192
5+
192 × 2 = 384
6+
192 × 3 = 576
7+
8+
By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call
9+
192384576 the concatenated product of 192 and (1,2,3)
10+
11+
The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5,
12+
giving the pandigital, 918273645, which is the concatenated product of 9 and
13+
(1,2,3,4,5).
14+
15+
What is the largest 1 to 9 pandigital 9-digit number that can be formed as the
16+
concatenated product of an integer with (1,2, ... , n) where n > 1?
17+
"""
18+
19+
20+
def is_9_palindromic(n: int) -> bool:
21+
"""
22+
Checks whether n is a 9-digit 1 to 9 pandigital number.
23+
>>> is_9_palindromic(12345)
24+
False
25+
>>> is_9_palindromic(156284973)
26+
True
27+
>>> is_9_palindromic(1562849733)
28+
False
29+
"""
30+
s = str(n)
31+
return len(s) == 9 and set(s) == set("123456789")
32+
33+
34+
def solution() -> int:
35+
"""
36+
Return the largest 1 to 9 pandigital 9-digital number that can be formed as the
37+
concatenated product of an integer with (1,2,...,n) where n > 1.
38+
39+
Solution:
40+
Since n>1, the largest candidate for the solution will be a concactenation of
41+
a 4-digit number and its double, a 5-digit number.
42+
Let a be the 4-digit number.
43+
a has 4 digits => 1000 <= a < 10000
44+
2a has 5 digits => 10000 <= 2a < 100000
45+
=> 5000 <= a < 10000
46+
47+
The concatenation of a with 2a = a * 10^5 + 2a
48+
so our candidate for a given a is 100002 * a.
49+
We iterate through the search space 5000 <= a < 10000 in reverse order,
50+
calculating the candidates for each a and checking if they are 1-9 pandigital.
51+
52+
In case there are no 4-digit numbers that satisfy this property, we check
53+
the 3-digit numbers with a similar formula (the example a=192 gives a lower
54+
bound on the length of a):
55+
a has 3 digits, etc...
56+
=> 100 <= a < 334, candidate = a * 10^6 + 2a * 10^3 + 3a
57+
= 1002003 * a
58+
59+
"""
60+
for base_num in range(9999, 4999, -1):
61+
candidate = 100002 * base_num
62+
if is_9_palindromic(candidate):
63+
return candidate
64+
65+
for base_num in range(333, 99, -1):
66+
candidate = 1002003 * base_num
67+
if is_9_palindromic(candidate):
68+
return candidate
69+
70+
return 192384576
71+
72+
73+
if __name__ == "__main__":
74+
print(solution())

0 commit comments

Comments
 (0)