TheAlgorithms-Python

Форк
0
48 строк · 980.0 Байт
1
"""
2
Project Euler Problem 2: https://projecteuler.net/problem=2
3

4
Even Fibonacci Numbers
5

6
Each new term in the Fibonacci sequence is generated by adding the previous
7
two terms. By starting with 1 and 2, the first 10 terms will be:
8

9
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
10

11
By considering the terms in the Fibonacci sequence whose values do not exceed
12
four million, find the sum of the even-valued terms.
13

14
References:
15
    - https://en.wikipedia.org/wiki/Fibonacci_number
16
"""
17

18

19
def 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
    if n <= 1:
37
        return 0
38
    a = 0
39
    b = 2
40
    count = 0
41
    while 4 * b + a <= n:
42
        a, b = b, 4 * b + a
43
        count += a
44
    return count + b
45

46

47
if __name__ == "__main__":
48
    print(f"{solution() = }")
49

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.