-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem2.py
31 lines (28 loc) · 1009 Bytes
/
problem2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 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, ...
#
# Find the sum of all the even-valued terms in the sequence
# which do not exceed four million.
#
# Answer: 461372
# A recursive function makes the most sense dealing with
# Fibonacci numbers since the value of any number depends on
# every previous number
# User only needs to define the ceiling (largest number above
# which to stop)
def sumEvenFib(ceiling, total = 0, prev = 1, this = 2):
next = prev + this
if this <= ceiling:
# if this is even, add it to the total and pass along
if not (this % 2):
return sumEvenFib(ceiling, total + this, this, next)
# otherwise just pass along the current total
else:
return sumEvenFib(ceiling, total, this, next)
else:
return total
if __name__ == "__main__":
print sumEvenFib(4000000)