My solutions to the problems found at Project Euler.
Jump to: | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 16 | 17 | 20 | 21 | 22 | 25 | 3-2 |#! /usr/bin/python
# 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 fib(n):
"Generates a list of fibonacci numbers up to n-length"
if n <= 0:
return []
if n == 1:
return [1]
if n == 2:
return [1,2]
seq = [1,2]
position = 2
while len(seq) < n:
seq.append( seq[position-2] + seq[position-1] )
position += 1
return seq
if __name__ == "__main__":
# Search for the fib-seq who's highest value is closest to, but
# does not exceed 4,000,000
highest_val = 4000000
test = 3
while fib(test)[-1:][0] < highest_val:
test += 1
total = 0
for n in fib(test):
if n % 2 == 0:
total += n
print str(total) + ' is the total value of all even-numbered values in the fibonacci sequence ' + \
'that is closest to in highest value, but does not exceed, 4,000,000.'