How to Create a Prime Number Generator in Python?

Estimated read time 1 min read

You can create a prime number generator in Python using a similar algorithm as in the previous example, but using a generator function instead of a list to yield prime numbers one by one. Here’s an example code snippet:

def prime_generator(n):
    for num in range(2, n+1):
        for i in range(2, int(num**0.5) + 1):
            if (num % i) == 0:
                break
        else:
            yield num

# Example usage:
for prime in prime_generator(20):
    print(prime)

In this example, we define a prime_generator function that takes a positive integer n as input and yields prime numbers up to n one by one using the yield keyword.

We use a similar algorithm as in the previous example to check if a number is prime, but instead of appending prime numbers to a list, we use the yield keyword to yield the prime numbers one by one as a generator object.

Finally, we test the function by iterating over the generator object returned by prime_generator(20) using a for loop and printing each prime number one by one. You can modify this code to work with larger ranges of numbers or to input the number range from the user.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply