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

Function solution

project_euler/problem_002/sol5.py:19–48  ·  view source on GitHub ↗

Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44

(n: int = 4000000)

Source from the content-addressed store, hash-verified

17
18
19def solution(n: int = 4000000) -> int:
20 """
21 Returns the sum of all even fibonacci sequence elements that are lower
22 or equal to n.
23
24 >>> solution(10)
25 10
26 >>> solution(15)
27 10
28 >>> solution(2)
29 2
30 >>> solution(1)
31 0
32 >>> solution(34)
33 44
34 """
35
36 fib = [0, 1]
37 i = 0
38 while fib[i] <= n:
39 fib.append(fib[i] + fib[i + 1])
40 if fib[i + 2] > n:
41 break
42 i += 1
43 total = 0
44 for j in range(len(fib) - 1):
45 if fib[j] % 2 == 0:
46 total += fib[j]
47
48 return total
49
50
51if __name__ == "__main__":

Callers 1

sol5.pyFile · 0.70

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected