Python printing all prime numbers

I wrote code to print all prime numbers but i cant even understand it even tho i wrote it myself pls help!!!

num = 1

while True:
    for i in range(1,num):
        g = num%i
        if num%i == 0:
            print(f'{num} divided by {i}')
            num += 1
        print(f'Remainder {g}')        
    num += 1

its dividng every non-prime number by 1 but not dividing prime number by 1 i am totally confused this is the most confusing problem i have ever faced in my coding journey pls help!!!

This code:

  • sets i to 1
  • modulo num by i (1)
  • increments num
  • break for loop
  • increment num again at the bottom
  • loops

It keeps resetting i to 1 at the top of the while loop and increments num twice, so you are just dividing every even number by 1.

2 is a prime number as well.

2 divided by 1
Remainder 0
4 divided by 1
Remainder 0

In my opinion, the method you used is a very inefficient. As it grows with a O(N^2) rate (it will take a lot of time with larger numbers). While it could be difficult to understand, I recommend looking at geeks for geeks version of Atkin’s sieve.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.