-
Notifications
You must be signed in to change notification settings - Fork 16
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ec7e701
commit b299bcb
Showing
2 changed files
with
68 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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() |