Skip to content

Commit 145879b

Browse files
mindauglMaximSmolskiypre-commit-ci[bot]
authored
Add solution for the Euler project problem 164. (#12663)
* Add solution for the Euler project problem 164. * Update sol1.py * Update sol1.py * Update sol1.py * Update sol1.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update sol1.py --------- Co-authored-by: Maxim Smolskiy <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 0a3a965 commit 145879b

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

project_euler/problem_164/__init__.py

Whitespace-only changes.

project_euler/problem_164/sol1.py

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
"""
2+
Project Euler Problem 164: https://projecteuler.net/problem=164
3+
4+
Three Consecutive Digital Sum Limit
5+
6+
How many 20 digit numbers n (without any leading zero) exist such that no three
7+
consecutive digits of n have a sum greater than 9?
8+
9+
Brute-force recursive solution with caching of intermediate results.
10+
"""
11+
12+
13+
def solve(
14+
digit: int, prev1: int, prev2: int, sum_max: int, first: bool, cache: dict[str, int]
15+
) -> int:
16+
"""
17+
Solve for remaining 'digit' digits, with previous 'prev1' digit, and
18+
previous-previous 'prev2' digit, total sum of 'sum_max'.
19+
Pass around 'cache' to store/reuse intermediate results.
20+
21+
>>> solve(digit=1, prev1=0, prev2=0, sum_max=9, first=True, cache={})
22+
9
23+
>>> solve(digit=1, prev1=0, prev2=0, sum_max=9, first=False, cache={})
24+
10
25+
"""
26+
if digit == 0:
27+
return 1
28+
29+
cache_str = f"{digit},{prev1},{prev2}"
30+
if cache_str in cache:
31+
return cache[cache_str]
32+
33+
comb = 0
34+
for curr in range(sum_max - prev1 - prev2 + 1):
35+
if first and curr == 0:
36+
continue
37+
38+
comb += solve(
39+
digit=digit - 1,
40+
prev1=curr,
41+
prev2=prev1,
42+
sum_max=sum_max,
43+
first=False,
44+
cache=cache,
45+
)
46+
47+
cache[cache_str] = comb
48+
return comb
49+
50+
51+
def solution(n_digits: int = 20) -> int:
52+
"""
53+
Solves the problem for n_digits number of digits.
54+
55+
>>> solution(2)
56+
45
57+
>>> solution(10)
58+
21838806
59+
"""
60+
cache: dict[str, int] = {}
61+
return solve(digit=n_digits, prev1=0, prev2=0, sum_max=9, first=True, cache=cache)
62+
63+
64+
if __name__ == "__main__":
65+
print(f"{solution(10) = }")

0 commit comments

Comments
 (0)