Skip to content

Commit

Permalink
Solved the problem 2
Browse files Browse the repository at this point in the history
  • Loading branch information
dhruvbaldawa committed Dec 30, 2011
1 parent ec7e701 commit b299bcb
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 1 deletion.
8 changes: 7 additions & 1 deletion 0001-3and5.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import math
"""
Problem 1
Add all the natural numbers below one thousand that are multiples of 3 or 5.
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def bruteforce():
sum_ = 0
number = 1000
Expand Down
61 changes: 61 additions & 0 deletions 0002-fib-4m.py
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()

0 comments on commit b299bcb

Please sign in to comment.