Skip to content
GitHub no longer supports this web browser. Learn more about the browsers we support.
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time. Cannot retrieve contributors at this time
37 lines (34 sloc) 1021 Bytes
# -*- coding: utf-8 -*-
"""
Project Euler. Problem 2.
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.
"""
def fibonaccigen():
'''
Generator returns number from Fibonacci sequence
'''
n1 = 0
n2 = 1
while True:
n1 += n2
yield n1
n2 += n1
yield n2
def sumofeven(n):
'''
Returns sum of even Fibonacci numbers below number n
'''
if n <= 1:
return 0
fib = fibonaccigen()
nfib = next(fib)
evensum = 0
while nfib <= n:
if nfib % 2 == 0:
evensum += nfib
nfib = next(fib)
return evensum
n = int(input('Could you please write a number the sum below should be calculated: '))
print(sumofeven(n))
You can’t perform that action at this time.