Skip to content

Add solution for the Euler project problem 164. #12663

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Add solution for the Euler project problem 164.
  • Loading branch information
mindaugl committed Apr 8, 2025
commit 55a9a415cfcccad595054bf6a9d4a279abc0a3b2
Empty file.
58 changes: 58 additions & 0 deletions project_euler/problem_164/sol1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""
Project Euler Problem 164: https://projecteuler.net/problem=164

Three Consecutive Digital Sum Limit

How many 20 digit numbers n (without any leading zero) exist such that no three
consecutive digits of n have a sum greater than 9?

Brute-force recursive solution with caching of intermediate results.

>>> solution(10)
21838806
"""


def solve(
digit: int, prev: int, prev2: int, sum_max: int, first: bool, cache: dict[str, int]
) -> int:
"""
Solve for remaining 'digit' digits, with previous 'prev' number, and
previous-previous 'prev2' number, total sum of 'sum_max'.
Pass around 'cache' to store/reuse intermediate results.

>>> solve(1, 0, 0, 9, True, {})
9
>>> solve(1, 0, 0, 9, False, {})
10
"""
if digit == 0:
return 1
comb = 0
cache_str = f"{digit},{prev},{prev2}"
if cache_str in cache:
return cache[cache_str]
for v in range(sum_max - prev - prev2 + 1):
if first and v == 0:
continue
comb += solve(digit - 1, v, prev, sum_max, False, cache)
cache[cache_str] = comb
return comb


def solution(n_digits: int = 20) -> int:
"""
Solves the problem for n_digits number of digits.

>>> solution(2)
45
"""
sum_max = 9
cache: dict[str, int] = {}
ans = solve(n_digits, 0, 0, sum_max, True, cache)

return ans


if __name__ == "__main__":
print(f"{solution(10) = }")