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):
        
        print(i)
        g = num%i
        if num%i == 0:
            print(f'{num} divided by {i}')
            
            num += 1
            break
        
    try:
          
        print(f'Remainder {g}')        
        print(num)
    except:
        print(num)
    
    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.

0
1
1
2 divided by 1
Remainder 0
3
1
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.