python - Using Fibonacci Program to Sum Even Elements -


i trying solve following using python:

each new term in fibonacci sequence generated adding previous 2 terms. starting 1 , 2, first 10 terms be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

by considering terms in fibonacci sequence values not exceed 4 million, find sum of even-valued terms.

so far, have been able generate fibonacci elements in trying sum elements, code seems stall. here code below:

def fib(n):     if n==0:         return 0     elif n==1:         return 1     if n>1:         return fib(n-1)+fib(n-2)  n=0 total=0  while fib(n)<=4000000:     if fib(n)%2==0:         total+=fib(n)  print(total) 

any suggestions welcome.

you have infinite loop n isn't ever incremented 0 in while loop. additionally, why not sum fibonacci total as as find next fibonacci value in same while loop, this:

x= 1 y=1 total = 0 while x <= 4000000:     if x % 2 == 0:         total += x     x, y = y, x + y      print (total) 

outputs:

4613732 

Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -