Permalink
Join GitHub today
GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.
Sign up
Fetching contributors…
Cannot retrieve contributors at this time.
Cannot retrieve contributors at this time
| # -*- 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)) |