Project Euler # 2 "Even Fibonacci Numbers" in Python

Problem 2 "Even Fibonacci Number"

The Fibonacci sequence terms are the sum of the previous two terms. If the first two terms are 1, 2, then the first 10 terms are: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Find the sum of even-valued terms with a sequence term value of 4 million or less.

Python


fibs = [1, 2]
while True:
  next_fib = sum(fibs[-2:])
  if(next_fib <= 4000000):
    fibs.append(next_fib)
  else:
    break

result = 0
for i in fibs:
  if(i % 2 == 0):
    result += i
print result
print result == 4613732

result


4613732
True

Postscript

It seems that the result part can be written concisely by using the list comprehension notation.

Python


result = sum([i for i in fibs if i % 2 == 0])

Recommended Posts

Project Euler # 2 "Even Fibonacci Numbers" in Python
Project Euler # 10 "sum of prime numbers" in Python
Functional programming in Python Project Euler 1
[Note] Project Euler in Python (Problem 1-22)
Functional programming in Python Project Euler 3
Project Euler # 5 "Minimum Multiples" in Python
Functional programming in Python Project Euler 2
Project Euler # 4 "Maximum Palindrome" in Python
Project Euler # 3 "Maximum Prime Factors" in Python
Project Euler # 11 "Maximum Product in Grid" in Python
Project Euler # 16 "Sum of Powers" in Python
Project Euler # 9 "Special Pythagorean Triple" in Python
Project Euler # 14 "Longest Collatz Sequence" in Python
Project Euler # 17 "Number of Characters" in Python
Project Euler # 1 "Multiples of 3 and 5" in Python
Prime numbers in Python
Project Euler # 8 "Maximum Product in Number String" in Python
Project Euler # 12 "High Divisibility Triangular Number" in Python
Handle complex numbers in Python
Project Euler 10 "Sum of Prime Numbers"
Create Python project documentation in Sphinx
Law of large numbers in python
Project Euler 37
Project Euler 47
Project Euler 31
Project Euler 4
Project Euler 38
Project Euler 26
Project Euler 8
Project Euler 22
Project Euler 19
Project Euler 50
Project Euler 33
Project Euler 32
Project Euler 43
Project Euler 35
Project Euler 36
Project Euler 24
Project Euler 48
Project Euler 45
Project Euler 6
Project Euler 44
Project Euler 39
Project Euler 40
Project Euler 49
Project Euler 29
Project Euler 27
Project Euler 41
Project Euler 18
Project Euler 13
Project Euler 30
Project Euler 16
Project Euler 14
Project Euler 34
Project Euler 25
Do a non-recursive Euler Tour in Python
I searched for prime numbers in python
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python