TheAlgorithms-Python
48 строк · 980.0 Байт
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
18
19def solution(n: int = 4000000) -> int:
20"""
21Returns the sum of all even fibonacci sequence elements that are lower
22or equal to n.
23
24>>> solution(10)
2510
26>>> solution(15)
2710
28>>> solution(2)
292
30>>> solution(1)
310
32>>> solution(34)
3344
34"""
35
36if n <= 1:
37return 0
38a = 0
39b = 2
40count = 0
41while 4 * b + a <= n:
42a, b = b, 4 * b + a
43count += a
44return count + b
45
46
47if __name__ == "__main__":
48print(f"{solution() = }")
49