Monday, April 15, 2013

Project Euler : Intro and Solution to first 2 problems.

Project Euler is a site for mathematicians and programmers with numerous mathematical problems. I will be writing solutions in Python2.7. If you have a better approach or solution to these problems, please share.
I will be happy to take criticisms about my work. Also, if you know any other sources that offer such problems, please let us know.

Problem 1 : Multiples of 3 and 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.
Solution:
1
2
3
4
5
6
7
8
def multi3and5(upto):
     i = 1        # initializing loop variable i
     sum = 0
     while i < upto:        # loop will iterate while i is less than 'upto' which is 1000 in our problem
             if i % 3 == 0 or i % 5 == 0:        # if i is dividable by either 3 or 5,
                     sum = sum + i        # add the number i to sum
             i = i + 1        # incrementing loop counter
     return sum        # after final iteration, sum will hold the answer


Problem 2 : Even Fibonacci numbers

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 terms.
Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def evenFibSum(upto):
    sum = 0        # initializing sum and fib to 0
    fib = 0
    num1 = 0        # the Fibonacci series starts with 0 being the first number 
    num2 = 1        # and 1 being the second number
# we loop will iterate until num2 is less than 'upto' which is 4000000 in our problem
    while num2 < upto:        
            if num2 % 2 == 0:        # if num2 is even..
                    sum = sum + num2        # add it to the sum
            fib = num1 + num2        # fib will have addition of num1 and num2
            num1 = num2        # now that we're done adding num1 and num2, our new num1 will be num2
            num2 = fib        # and num2 will be addition of fib, which was addition of previous num1 and num2
# so in next iteration, num1 will be num2 of previous iteration
# and num2 will be fib of previous iteration
    return sum        # finally, return the sum


That's it for now, I'll be back with solutions to next 2 problems soon. *Note: I prefer writing generalized solutions by providing an option to pass arguments to functions whenever possible. The purpose of these posts is not to help you cheat with Project Euler's problems, but rather give you an understanding of how mathematical problems can be solved with programming. Which is why I've not given exact answers, but the code that'll give you correct answer. You are to understand it and type it out yourself to see how it works.