Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Solved the problem 2

  • Loading branch information...
commit b299bcb59f95642d6ed6f9db370eaabcc8c53d2b 1 parent ec7e701
@dhruvbaldawa authored
Showing with 68 additions and 1 deletion.
  1. +7 −1 0001-3and5.py
  2. +61 −0 0002-fib-4m.py
View
8 0001-3and5.py
@@ -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
View
61 0002-fib-4m.py
@@ -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()
Please sign in to comment.
Something went wrong with that request. Please try again.