[Solved] C++ – Printing prime numbers till N [closed]


First for future reference you should probably post that on code review, unless there is a specific problem then you should create a Minimal, Complete, and Verifiable post.

There is nothing inherently wrong other than you do not check that N>0 which could lead to an infinite loop, j should be going to i not N, and I think this would print 1 as a prime number which it is not. Here are some pointers:

  1. Why are you going from N to 0? That seems a little counter intuitive compared from going from 2 to N (you can skip 1 since it is not prime)

  2. If you are going to use a flag (u) then you should make it a bool which forces it to be either true or false

  3. You do not need to do a flag, instead as soon as you find a divisor print the number and then break the inner loop like

    for(j=2; j< N-1; j++){
       if(i%j==0){
         cout << i << " ";
         break;
        }
     }
    
  4. You do not need to have j go all the way to i, just the sqrt(i) since anything greater then the sqrt(i) that divides i must must be multiplied by some number smaller then the sqrt(i). So if i is not prime, then there must be a divisor below sqrt(i)

1

solved C++ – Printing prime numbers till N [closed]