MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / solution

Function solution

project_euler/problem_002/sol4.py:22–69  ·  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 >>> solution(3.4) 2 >>> solution(0) Traceback (most

(n: int = 4000000)

Source from the content-addressed store, hash-verified

20
21
22def solution(n: int = 4000000) -> int:
23 """
24 Returns the sum of all even fibonacci sequence elements that are lower
25 or equal to n.
26
27 >>> solution(10)
28 10
29 >>> solution(15)
30 10
31 >>> solution(2)
32 2
33 >>> solution(1)
34 0
35 >>> solution(34)
36 44
37 >>> solution(3.4)
38 2
39 >>> solution(0)
40 Traceback (most recent call last):
41 ...
42 ValueError: Parameter n must be greater than or equal to one.
43 >>> solution(-17)
44 Traceback (most recent call last):
45 ...
46 ValueError: Parameter n must be greater than or equal to one.
47 >>> solution([])
48 Traceback (most recent call last):
49 ...
50 TypeError: Parameter n must be int or castable to int.
51 >>> solution("asd")
52 Traceback (most recent call last):
53 ...
54 TypeError: Parameter n must be int or castable to int.
55 """
56
57 try:
58 n = int(n)
59 except TypeError, ValueError:
60 raise TypeError("Parameter n must be int or castable to int.")
61 if n <= 0:
62 raise ValueError("Parameter n must be greater than or equal to one.")
63 getcontext().prec = 100
64 phi = (Decimal(5) ** Decimal("0.5") + 1) / Decimal(2)
65
66 index = (math.floor(math.log(n * (phi + 2), phi) - 1) // 3) * 3 + 2
67 num = Decimal(round(phi ** Decimal(index + 1))) / (phi + 2)
68 total = num // 2
69 return int(total)
70
71
72if __name__ == "__main__":

Callers 1

sol4.pyFile · 0.70

Calls 1

floorMethod · 0.80

Tested by

no test coverage detected