49 lines
1.1 KiB
Python
49 lines
1.1 KiB
Python
"""
|
||
Even Fibonacci Numbers
|
||
|
||
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
|
||
1, 2, 3, 5, 8, 13, 21, 34, 55, 89
|
||
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
|
||
"""
|
||
|
||
UP_NUM = 4000000
|
||
|
||
|
||
def is_even(num: int) -> bool:
|
||
"""Check if a number is even."""
|
||
return num & 1 == 0
|
||
|
||
|
||
"""
|
||
下面这个方法实在太慢,计算400万项还会内存溢出。
|
||
```python
|
||
def fibonacci_sequence(n: int) -> list[int]:
|
||
a, b = 1, 2
|
||
res = [a, b]
|
||
while b <= n:
|
||
a, b = b, a + b
|
||
res.append(b)
|
||
return res
|
||
|
||
|
||
def main():
|
||
fib_seq = fibonacci_sequence(UP_NUM)
|
||
even_sum = sum(num for num in fib_seq if is_even(num))
|
||
print(even_sum)
|
||
```
|
||
"""
|
||
|
||
|
||
def even_fibonacci(limit: int) -> int:
|
||
a, b = 1, 2
|
||
even_sum = 0
|
||
while b <= limit:
|
||
if is_even(b):
|
||
even_sum += b
|
||
a, b = b, a + b
|
||
return even_sum
|
||
|
||
|
||
if __name__ == "__main__":
|
||
print(even_fibonacci(UP_NUM))
|