'How to make an infinite generator in python to all prime numbers?

I was trying to make this infinite generator in python:

import math
def all_primes():
    count = 2
    while True:
        flag = True
        for x in range(2, int(math.sqrt(count) + 1)):
            if count % x == 0: 
                flag = False
        
        if flag:
            yield count
        else:
            count += 1
            
for i in all_primes():
    print(i)

but in the output it always gives me 2. Why is that?



Solution 1:[1]

The reason your code is always yielding '3' is that 'flag' is always true. Working through the math in the for loop with int(math.sqrt(count)+1) makes it so the loop only goes from 2 -> 2. So the only thing checked is if 3 % 2 == 0 which is never true. Therefore flag is always false and the count is never incremented.

Solution 2:[2]

Thats because the for loop is never itering. If count=3 then int(math.sqrt(count) + 1) is gonna return 2, so the range of your for loop is gonna be (2,2), therefore it will never iterate, and the flag value is not going to change, and therefore count value is always gonna be the same.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jerry Spice
Solution 2 Nestor Silva