Let’s write a Python program to generate Fibonacci series. We will also write a program to generate the prime numbers in a Fibonacci series.

What is a Fibonacci series?

The Fibonacci Series is a series of numbers in which the first number is 0 and the second number is 1. The third number is the sum of first number and second number. Each number thereafter is the sum of the previous two numbers in the series. A few numbers from the Fibonacci series are given below.

  • 0, 1, 1, 2, 3, 5, 8

How to generate Fibonacci series?

To generate Fibonacci number series, we create a loop which iterates upto the given number N. Before loop starts, the first and second numbers of the series are initialized with 0 and 1 respectively. Within the loop, a third variable is used to add the previous two Fibonacci numbers.

Python code (to generate Fibonacci series)

The Python program given below generates the Fibonacci series numbers upto a given limit.

#Python program to generate Fibonacci Series

limit = int(input("Enter a limit "))
print("The Fibonacci Series is")
f1=0
f2=1
print(f1)
print(f2)
f3=f1+f2
while f3<=limit:
    print(f3)
    f1=f2
    f2=f3
    f3=f1+f2

Python program (to generate Prime Fibonacci series)

The code above can be modified to print only the prime numbers from the Fibonacci series. Each number of the Fibonacci Series is checked whether it is prime or not. If it is a prime number, it is printed.

#Function to check if a number is prime or not
def isPrime(n):
    i=2
    while i<n:
        if n%i == 0:
            return False    #number is not a prime number
            break
        i = i + 1
    else:
        return True         #number is a prime number
    
#Python program to generate Prime numbers in Fibonacci Series
limit = int(input("Enter a limit "))
print("The Prime numbers in Fibonacci Series are")
f1=0
f2=1
print(f1)
print(f2)
f3=f1+f2
while f3<=limit:
    if isPrime(f3):
        print(f3)
    f1=f2
    f2=f3
    f3=f1+f2
Last modified: March 19, 2023

Author