-
Notifications
You must be signed in to change notification settings - Fork 16
/
0002-fib-4m.py
61 lines (54 loc) · 1.39 KB
/
0002-fib-4m.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""
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 t
"""
def fibonacci():
"""
Just the usual fibonacci generator which starts from 1,2,3,..
"""
a = 1
b = 2
while True:
yield a
sum_ = a + b
a = b
b = sum_
def mod_fibonacci():
"""
A modified version which returns every third number from 1,1,2,3,5,8,..
Note: Every third number is an even number
"""
a = 1
b = 1
c = a + b
while True:
yield c
a = b + c
b = c + a
c = a + b
def traditional():
"""
Function to calculate sum of the usual fibonacci
"""
sum_ = 0
for x in fibonacci():
if x >= 4000000:
break
if x % 2 == 0:
sum_ = sum_ + x
return sum_
def third_number():
"""
Function to calculate the sum out of the modified fibonacci
"""
sum_ = 0
for x in mod_fibonacci():
print x
if x >= 4000000:
break
sum_ = sum_ + x
return sum_
print "Answer by traditional method:",traditional()
print "Answer by optimized method:",third_number()