Skip to content

[pull] master from TheAlgorithms:master #112

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

Merged
merged 2 commits into from
May 5, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Add solution for the Euler project problem 164. (TheAlgorithms#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 <mithridatus@mail.ru>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
3 people authored May 5, 2025
commit 145879b8b2546c74fc51446ac607823876a0f601
Empty file.
65 changes: 65 additions & 0 deletions project_euler/problem_164/sol1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""
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.
"""


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

>>> solve(digit=1, prev1=0, prev2=0, sum_max=9, first=True, cache={})
9
>>> solve(digit=1, prev1=0, prev2=0, sum_max=9, first=False, cache={})
10
"""
if digit == 0:
return 1

cache_str = f"{digit},{prev1},{prev2}"
if cache_str in cache:
return cache[cache_str]

comb = 0
for curr in range(sum_max - prev1 - prev2 + 1):
if first and curr == 0:
continue

comb += solve(
digit=digit - 1,
prev1=curr,
prev2=prev1,
sum_max=sum_max,
first=False,
cache=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
>>> solution(10)
21838806
"""
cache: dict[str, int] = {}
return solve(digit=n_digits, prev1=0, prev2=0, sum_max=9, first=True, cache=cache)


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