TheAlgorithms-Python
73 строки · 1.9 Кб
1"""
2Project Euler Problem 2: https://projecteuler.net/problem=2
3
4Even Fibonacci Numbers
5
6Each new term in the Fibonacci sequence is generated by adding the previous
7two terms. By starting with 1 and 2, the first 10 terms will be:
8
91, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
10
11By considering the terms in the Fibonacci sequence whose values do not exceed
12four million, find the sum of the even-valued terms.
13
14References:
15- https://en.wikipedia.org/wiki/Fibonacci_number
16"""
17
18import math19from decimal import Decimal, getcontext20
21
22def solution(n: int = 4000000) -> int:23"""24Returns the sum of all even fibonacci sequence elements that are lower
25or equal to n.
26
27>>> solution(10)
2810
29>>> solution(15)
3010
31>>> solution(2)
322
33>>> solution(1)
340
35>>> solution(34)
3644
37>>> solution(3.4)
382
39>>> solution(0)
40Traceback (most recent call last):
41...
42ValueError: Parameter n must be greater than or equal to one.
43>>> solution(-17)
44Traceback (most recent call last):
45...
46ValueError: Parameter n must be greater than or equal to one.
47>>> solution([])
48Traceback (most recent call last):
49...
50TypeError: Parameter n must be int or castable to int.
51>>> solution("asd")
52Traceback (most recent call last):
53...
54TypeError: Parameter n must be int or castable to int.
55"""
56
57try:58n = int(n)59except (TypeError, ValueError):60raise TypeError("Parameter n must be int or castable to int.")61if n <= 0:62raise ValueError("Parameter n must be greater than or equal to one.")63getcontext().prec = 10064phi = (Decimal(5) ** Decimal(0.5) + 1) / Decimal(2)65
66index = (math.floor(math.log(n * (phi + 2), phi) - 1) // 3) * 3 + 267num = Decimal(round(phi ** Decimal(index + 1))) / (phi + 2)68total = num // 269return int(total)70
71
72if __name__ == "__main__":73print(f"{solution() = }")74