An iterative algorithm for Fibonacci numbers

fibonacci series
algorithm for fibonacci series
pseudo code for fibonacci series
iterative fibonacci c++
fibonacci sequence coding
fibonacci series using iteration java
nth fibonacci number formula
fibonacci series using function

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

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

Fibonacci: Recursion vs Iteration - DEV Community ‍ ‍ , Tagged with java, beginners, algorithm, codenewbie. Write a function to generate the nth Fibonacci number. Solution #2 Using Iteration. Fibonacci Iterative Algorithm. First we try to draft the iterative algorithm for Fibonacci series. Procedure Fibonacci(n) declare f 0, f 1, fib, loop set f 0 to 0 set f 1 to 1 display f 0, f 1 for loop ← 1 to n fib ← f 0 + f 1 f 0 ← f 1 f 1 ← fib display fib end for end procedure

You are returning a value within a loop, so the function is exiting before the value of y ever gets to be any more than 1.

If I may suggest something shorter, and much more pythonful:

def fibs(n):                                                                                                 
    fibs = [0, 1, 1]                                                                                           
    for f in range(2, n):                                                                                      
        fibs.append(fibs[-1] + fibs[-2])                                                                         
    return fibs[n]

This will do exactly the same thing as your algorithm, but instead of creating three temporary variables, it just adds them into a list, and returns the nth fibonacci number by index.

Data Structure & Algorithms Fibonacci Series, Fibonacci Iterative Algorithm. First we try to draft the iterative algorithm for Fibonacci series. Procedure Fibonacci(n)  Write an iterative algorithm to compute the n th Fibonacci number. Our team of expert educators are currently working on this. Get notified when this problem is solved.

On fib(0), you're returning 0 because:

if (n == 0) {
    return 0;
}

On fib(1), you're returning 1 because:

y = 1
return y

On fig(2), you're returning 1 because:

y = 1
return y

...and so on. As long as return y is inside your loop, the function is ending on the first iteration of your for loop every time.

Here's a good solution that another user came up with: How to write the Fibonacci Sequence in Python

Space efficient iterative method to Fibonacci number, We have discussed below recursive solution in method 4 of Program for Fibonacci numbers. F[2][2] = |1, 1| |1, 0| M[2][2] = |1, 1| |1, 0| F[n][n] = fib(n) | fib(n-1​)  A common whiteboard problem that I have been asked to solve couple times, has been to "write a function to generate the nth Fibonacci number starting from 0,1".In this post, however, I want to address a common follow up question for this problem and that is what method is more efficient for solving this problem Recursion or Iteration.

Non recursive Fibonacci sequence in python

def fibs(n):
    f = []
    a = 0
    b = 1
    if n == 0 or n == 1:
        print n
    else:
        f.append(a)
        f.append(b)
        while len(f) != n:
            temp = a + b
            f.append(temp)
            a = b
            b = temp

    print f

fibs(10)

Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Fibonacci Numbers, Introduction to analysis of algorithms. An algorithm is just the outline or idea behind a program. We express algorithms in pseudo-code: something resembling C or  Fibonacci series: fib(n) = fib(n-1) + fib(n-2) → for n > 1. fib(n) = n→ for n ≤1. Fibonacci can be solved iteratively as well as recursively. The recursive approach seems to be much simpler and smaller, but there is a caveat, as it is calculating the Fibonacci of a number multiple times.

def fibiter(n):
    f1=1
    f2=1
    tmp=int()
    for i in range(1,int(n)-1):
        tmp = f1+f2
        f1=f2
        f2=tmp
    return f2

or with parallel assignment:

def fibiter(n):
    f1=1
    f2=1
    for i in range(1,int(n)-1):
        f1,f2=f2,f1+f2
    return f2

print fibiter(4)

[PDF] Twelve Simple Algorithms to Compute Fibonacci Numbers arXiv , The formal definition of this sequence directly maps to an algorithm to compute the nth Fibonacci number Fn. However, there are many other. One iterative approach we can take on this is calculating fibonacci from N = 0 to N = Target_N, as we do so we can keep track of the previous results of fibonacci for N-1 and N-2

Fibonacci, Fibonacci program - Both iterative and recursive versions. * Fibonacci series - 1,1 Iterative implementation for nth fibonacci number public int fibonacciIterative(​int n) {. if(n <= 1) { His recursive Fibonacci algorithm is the naive one which is  This another O(n) which relies on the fact that if we n times multiply the matrix M = {{1,1},{1,0}} to itself (in other words calculate power(M, n )), then we get the (n+1)th Fibonacci number as the element at row and column (0, 0) in the resultant matrix. The matrix representation gives the following closed expression for the Fibonacci numbers:

Iteration and Recursion in Python, -- this concept blew my mind). A recursive solution to find the nth Fibonacci number is: def F(n): if (n == 0): return 0 elif (n ==  In this tutorial we will learn to find Fibonacci series using recursion. Fibonacci series are the numbers in the following sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Fibonacci Iterative vs. Recursive - Syed Tousif Ahmed, simpler and smaller, but there is a caveat, as it is calculating the Fibonacci of a number multiple times. The time complexity of the iterative code is linear… A fast and simple O(logn) iteration algorithm for individual Lucas numbers is given. This is faster than using Fibonacci based methods because of the structure of Lucas numbers. Using a √5 conversion factor gives a faster Fibonacci algorithm because the speed up proposed in [5] also directly applies.

Comments
  • A post worth looking at if you are interested in complexity of your algorithm for Fibonacci series.
  • public int[] get(int limit) { int[] elements = new int[limit]; if (limit == 0) { return null; } elements[0] = 1; elements[1] = 1; for (int i = 2; i < limit; i++) { elements[i] = elements[i - 2] + elements[i - 1]; } return elements; } Can you verify this one ?
  • @Adelin What language is that? This is a Python question and that’s not Python code. Consider creating a new question, or ask on codereview.SE for review of your code. That being said, your array size is wrong for limit=1 which will give you an index exception.
  • Returning a at the end of the script is the computation of f(n - 1) and not f(n). You should return b to have f(n) returned
  • @eton_ceb That depends on your definition of the Fibonacci sequence. I usually start the sequence with 0 and 1 instead of 1 and 1.
  • You can ignore i and just write for _ in range(n)
  • This will take much more memory though as it needs to keep them all in the list (you’d notice it for very large n). Also I don’t think this is the best pythonic solution for this. I think using tuple (un)packing in a simple for loop (see edit to my answer) would be even nicer.
  • i would go one step further and say that although this solution is iterative, it has the same drawback as the recursive solution in the sense that it doesn't run in constant space. you've just replaced the stackframes with list elements.
  • @KebertX I know this thread is old but why does a,b = b,a+b inside the for loop work and not when you write it like this a=b and b = a+b? i mean a,b = b,a+b is just a = b and b = a+b right?
  • @HalcyonAbrahamRamirez: Tuple assignment is not the same as sequentially assigning each right side expressions to its respective "variable": with tuple assignment, the last evaluation is done before the first assignment - consider swapping: a, b = b, a
  • (wherever those curly braces came from… from __future__ import braces? :P)
  • Does this answer did I not implement it right ? ?
  • Fibonacci series values: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711,..... Please compare the values of your output with this values
  • I don't have output. I happen to know OEIS A000045, and to be the one to try and improve the presentation of a 2013/2 question in '17/1.