DEV Community

steelbeginner
steelbeginner

Posted on

Fibonacci sequence

Hello guys,
i know most of you have heard of the famous Fibonacci sequence in most dev practices and probably dev job interview. Am gonna show you how to write out the the sequence for any number of inputs desired. I am using python for this implementation.

Method 1: using resursion

This is usually the easiest way to do it because it has lines of code but can mean to be difficult to understand if you dont know the recursion principle itself. So if you dont know what recursion mean i suggest you pause a lil while and hit google or you can check out the next method and research later.

# function to define the logic using the recursion method
def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)


nterms = int(input())
# check if the number of terms is valid
if nterms <= 0:
    print("Plese enter a positive integer")
else:
    print("Fibonacci sequence:")
    for i in range(nterms):
        print(
            f"{fibonacci(i)} ", end=""
        )  # this is prints out the sequence on a single line. 

Method 2: using Loops

This method seems more familiar with everyone who knows basic programming principles like loops and conditionals. It has relatively more lines of code than the recursion method but its worth knowing too.

#Function for nth Fibonacci number

nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
    print("Please enter a positive integer")
elif nterms == 1:
    print("Fibonacci sequence upto", nterms, ":")
    print(n1)
else:
    print("Fibonacci sequence:")
    while count < nterms:
        print(n1)
        nth = n1 + n2
        # update values
        n1 = n2
        n2 = nth
        count += 1

Thank you for reading and dont forget to follow for more cool stuff like this from me... Blessings.

Top comments (0)