Saturday, September 19, 2020

First N Prime Numbers with Python

# python program to generate the first N prime numbers.
from math import sqrt
def number():
    '''Infinite Generator function to yield natural numbers'''
    num = 2
    while True:
        yield num
        num += 1
def main():
    # accept number of prime number to generate as N
    N = int(input("Enter count of prime numbers to generate : "))
    # counter to track prime numbers generated
    count = 0
    # initialize the generator
    gen = number()
    # while sufficient prime number have not been generated
    while count < N:
        # get the next natural number to check if it is prime
        n = next(gen)
        s = int(sqrt(n))
        # check for factors
        for i in range(2, s):
            if (i % 2) == 0:
                break
        # if no factors are found the number is prime
        else:
            print(n, " is a prime number")
            count += 1
if __name__ == '__main__':
    main()