Sometimes, we want to create a simple prime number generator in Python.
In this article, we’ll look at how to create a simple prime number generator in Python.
How to create a simple prime number generator in Python?
To create a simple prime number generator in Python, we can create a loop that checks each number being looped through is a prime.
For instance, we write
import math
def main():
count = 3
while True:
isprime = True
for x in range(2, int(math.sqrt(count) + 1)):
if count % x == 0:
isprime = False
break
if isprime:
print(count)
count += 1
to create the main
function that has a while loop that loops from 2 to the square root of count
plus 1 rounded to the nearest integer.
Then we divide count
by x
and get remainder 0, we know count
isn’t a prime.
And we set isprime
to False
and break the while loop.
Then we print the count
if count
is a prime.
At the end of the loop iteration, we increment count
by 1.
Conclusion
To create a simple prime number generator in Python, we can create a loop that checks each number being looped through is a prime.