Python Program to Find First N Prime Numbers

To write a program to find first N Prime Numbers in Python we should know how to find whether a Number is Prime Number or Not?

To find whether a Number is Prime Number or Not, you can check out the following link:
Python Program to find Prime Number or Not

Program code to find first n prime numbers in Python:

# Python Program to find first n prime numbers
from math import sqrt

# To take input from the user and initialize the variables
num = int(input("Enter a number: "))
count = 0
n = 2

print("First", num, "prime numbers are: ")
while count < num:
    # define a flag variable
    prime_flag = True
    
    for i in range(2, int(sqrt(n)) + 1):
        if (n % i) == 0:
            prime_flag = False
            break
    
    # check if flag is True
    if prime_flag:
        print(n, end =" ")
        count = count + 1
    n = n + 1

Output:

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *