简体   繁体   中英

Even valued terms sum in fibonacci, limit is 4 million

def fib(n):
   if n<= 1: 
       return n 
   else: 
       return(fib(n-1)+fib(n-2))

def comp():
   L=[]
   for i in range(1,4000000): 
        if i % 2 ==0:
           L.append(fib(i))
           return sum(L)
print(comp())

What is wrong with this code? It does not return anything but it looks good according to me.

The return statement is set to the wrong increment. It is executed the first time i % 2 == 0 becomes true (which is i == 2 in your case).

def fib(n):
   if n<= 1: 
       return n 
   else: 
       return(fib(n-1)+fib(n-2))

def comp():
   L=[]
   for i in range(1,4000000): 
        if i % 2 ==0:
           L.append(fib(i))
   return sum(L)

print(comp())

The above code is not going to work, though. Are you aware of how big this number would get?

Try

for i in range(1,40): 

as a start. It took quite a few seconds on my machine. Result is 63245985.

you should return sum(L) from function not from for loop follow below code

def fib(n):
    if n<= 1: 
        return n 
    else: 
        return(fib(n-1)+fib(n-2))

def comp():
    L=[]
    for i in range(1,20): 
        if i % 2 ==0:
            L.append(fib(i))
    return sum(L)

print(comp())

and other thing look at the range its too much,because of this it will take some time or may produce any memory related error, so reduce it for testing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM