MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / chain_length

Function chain_length

project_euler/problem_074/sol1.py:73–95  ·  view source on GitHub ↗

Calculate the length of the chain of non-repeating terms starting with n. Previous is a set containing the previous member of the chain. >>> chain_length(10101) 11 >>> chain_length(555) 20 >>> chain_length(178924) 39

(n: int, previous: set | None = None)

Source from the content-addressed store, hash-verified

71
72
73def chain_length(n: int, previous: set | None = None) -> int:
74 """
75 Calculate the length of the chain of non-repeating terms starting with n.
76 Previous is a set containing the previous member of the chain.
77 >>> chain_length(10101)
78 11
79 >>> chain_length(555)
80 20
81 >>> chain_length(178924)
82 39
83 """
84 previous = previous or set()
85 if n in CHAIN_LENGTH_CACHE:
86 return CHAIN_LENGTH_CACHE[n]
87 next_number = sum_digit_factorials(n)
88 if next_number in previous:
89 CHAIN_LENGTH_CACHE[n] = 0
90 return 0
91 else:
92 previous.add(n)
93 ret = 1 + chain_length(next_number, previous)
94 CHAIN_LENGTH_CACHE[n] = ret
95 return ret
96
97
98def solution(num_terms: int = 60, max_start: int = 1000000) -> int:

Callers 1

solutionFunction · 0.85

Calls 2

sum_digit_factorialsFunction · 0.85
addMethod · 0.45

Tested by

no test coverage detected