Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An iterative algorithm for Fibonacci numbers

Tags:

I am interested in an iterative algorithm for Fibonacci numbers, so I found the formula on wiki...it looks straight forward so I tried it in Python...it doesn't have a problem compiling and formula looks right...not sure why its giving the wrong output...did I not implement it right ?

def fib (n): 
    if( n == 0):
        return 0
    else:
        x = 0
        y = 1
        for i in range(1,n):
            z = (x + y)
            x = y
            y = z
            return y

for i in range(10):
    print (fib(i))

output

0
None
1
1
1
1
1
1

like image 330
Ris Avatar asked Feb 23 '13 23:02

Ris


People also ask

How do you create iterative Fibonacci algorithm?

Iterative Solution to find Fibonacci Sequence We use a while loop to find the sum of the first two terms and proceed with the series by interchanging the variables. We decrement the value of n and print the Fibonacci series till n-2 is greater than 0.

What is Fibonacci number calculate the recurrence relation for iterative Fibonacci algorithm?

The following recurrence relation defines the sequence Fn of Fibonacci numbers: F{n} = F{n-1} + F{n-2} with base values F(0) = 0 and F(1) = 1 . Following is the naive implementation in C, Java, and Python for finding the nth member of the Fibonacci sequence: C.


1 Answers

The problem is that your return y is within the loop of your function. So after the first iteration, it will already stop and return the first value: 1. Except when n is 0, in which case the function is made to return 0 itself, and in case n is 1, when the for loop will not iterate even once, and no return is being execute (hence the None return value).

To fix this, just move the return y outside of the loop.

Alternative implementation

Following KebertX’s example, here is a solution I would personally make in Python. Of course, if you were to process many Fibonacci values, you might even want to combine those two solutions and create a cache for the numbers.

def f(n):
    a, b = 0, 1
    for i in range(0, n):
        a, b = b, a + b
    return a
like image 174
poke Avatar answered Sep 21 '22 08:09

poke