Python | Find n-th Fibonacci number without recursion

Let us take a look at all the ways using which we can solve this problem.

Method 1: Using simple addition

def get_nth_fibonacci(n):

    a = 0
    b = 1
    if n < 0:
        print("Incorrect input. You cannot enter 0")
    elif n == 0:
        return a
    elif n == 1:
        return b
    else:
        for i in range(2, n):
            c = a + b
            a = b
            b = c
        return b

n = int(input("Enter the n-th fibonacci number you want: "))
print("The",n,"th fibonacci number is: ",get_nth_fibonacci(n))

Output:

Enter the n-th fibonacci number you want: 10
The 10 get_nth_fibonacci number is:  34

Explanation:
Here for 0 and 1, we defined conditions and for the other numbers we used else statements. Inside the else statement, we used a for loop that will run over the range from 2 to the number entered by the user. Now we add the first two numbers of Fibonacci and then assign the value of b in a and value of c in b. This will continue till the value of ” i “ reaches the mentioned range.

Method 2: Using append()

def get_nth_fibonacci(n):

    if n <= 0:
        return "Incorrect Output"
    data = [0, 1]
    if n > 2:
        for i in range(2, n):
            data.append(data[i-1] + data[i-2])
    return data[n-1]

n = int(input("Enter the n-th fibonacci number you want: "))
print("The",n,"th fibonacci number is: ",get_nth_fibonacci(n))

Explanation:

Here we defined the condition as stated for value 0 and for n > 2, we used for loop and as we go along we append the value that is computed by data[i-1] + data[i-2]. Decoding this for n = 10, then our first appended value will be data[2-1] + data[2-2] = data[1] + data[0] and the output will be 1+0 = 1. Now, this value will be appended to the list and this will continue till n reaches 9 because the last number in the range is excluded.

Here are the two approaches to solving the laid problem.

Share:

Author: Dhvanil V