TheAlgorithms-Python
48 строк · 960.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
36i = 137j = 238total = 039while j <= n:40if j % 2 == 0:41total += j42i, j = j, i + j43
44return total45
46
47if __name__ == "__main__":48print(f"{solution() = }")49