Project Euler #2 in "Python"

10,447

Solution 1

Your code isn't wrong, it's just too slow. In order to solve Project Euler problems, not only does your code have to be correct, but your algorithm must be efficient.

Your fibonacci computation is extremely expensive - that is, recursively trying to attain the next fibonacci number runs in O(2^n) time - far too long when you want to sum numbers with a limit of four million.

A more efficient implementation in Python is as follows:

x = 1
y = 1
z = 0
result = 0

while z < 4000000:
   z = (x+y)         
   if z%2 == 0:
       result = result + z

   #next iteration

   x = y
   y = z

print result

Solution 2

this definetly is not the only way- but another way of doing it.

def fib(number):
    series = [1,1]
    lastnum = (series[len(series)-1]+series[len(series)-2])
    _sum = 0
    while lastnum < number:
        if lastnum % 2 == 0:
            _sum += lastnum
        series.append(lastnum)
        lastnum = (series[len(series)-1] +series[len(series)-2])
    return series,_sum
Share:
10,447
Ashtrix
Author by

Ashtrix

Hey! An absolute noob here. Hope I catch up soon :)

Updated on June 04, 2022

Comments

  • Ashtrix
    Ashtrix almost 2 years

    I am an absolute beginner here. I was giving the questions on Project Euler a try in Python. Can you please point out where does my code go wrong?

    Q) 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.

    def fib(a):
        if ((a==0) or (a==1)):
            return 1
        else:
            return((fib(a-1))+(fib(a-2)))
        r=0
        sum=0
        while (fib(r))<4000000:
            if(((fib(r))%2)==0):
                sum+=fib(r)
                print(sum)