seeing if only the number entered i sPrime

Hi i'm looking at all the codes for prime numbers, but i dont want it to list all the other numbers up to it, just the number itself. i try erase the i++ and n++ but then it does nothing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 int num;
  bool prime;

  cout << "Please enter a positive integer" << endl;
  cin >> num;

  for(int i = 3; i <= num; i++){
    prime = true;
    for(int n = 2; n <= i - 1; n++){
      if(i % n == 0){
        prime = false;
      }
    }
    if(prime){
      cout << i << " is prime" << endl;
    }
  }
Take the last if() outside of the FOR loop. And change 'i' for 'num'.
Last edited on
when i take it out, it displays the "num is prime 3 times" (i chose the number 5).
even more when i do 11; it will just display more from there
Last edited on
That means you are not taking it out of the FOR loop. It actually sounds that you may have taken out the first if() out of the inner loop, not the last if() out of the outer loop.
i tried playing with bracket placement but i'm still not getting it

1
2
3
4
5
6
7
8
9
10
 for(int i = 3; i <= userNumber; i++){
    prime = true;
    for(int n = 2; n <= i - 1; n++){
      if(i % n == 0){
        prime = false;
      }
    
    
      cout << userNumber << " is prime" << endl;
    }}
i got it all working now. thx!
Topic archived. No new replies allowed.