Files
SolutionEuler/solutions/0000_0029/0002.even_fibonacci/euler_2.py
2025-12-26 17:35:14 +08:00

49 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
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))