To check for prime number with FOR loop

hello all, I am trying to write simple program to check entered number whether prime or not.

I haven't written any c++ program for a while, but did some search and wrote this but still suffering from serious issues. Any input is appreciated.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  #include <iostream>

using namespace std;
bool die(const string & msg);

int main() {
    
    unsigned x, i ;
    bool isPrime = true;
    
    cout << "Please enter a number: "; cin >> x;
    //if (!cin) die("Input failure");
   
    for ( i = 2 ;i<=x/2 ; ++i)
    {
    if (x%i == 0 )
    {
        isPrime = false;
        break;
        
    }
        if(isPrime)
            cout<<"This is a prime number:";
        else
            cout<<"This is not a prime number:";
    }
    }

bool die(const string & msg){
    
    cout << "Fatal Error: " << msg << endl;
    exit(EXIT_FAILURE);}
The problem with yours is that you're printing the result of each trial division. You're printing the (incomplete) results inside the loop. The solution is to move line 22-25 outside the for-loop.

Try something like this:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <cmath>

int main() { 
    int input{53}; 
        
    bool prime = true;
    for (int i = 2; (i * i) <= input; ++i)  
        if (! (input % i)) { prime = false; break; }
        
    std::cout << input << " is" << (prime? "": " not") << " prime.\n";    
}

http://coliru.stacked-crooked.com/a/bd1f03f445dea5be
Last edited on
Thanks, your suggestions seems to fix the issue, but I forgot to mention that the program also shouldn't quit and should be able to accept multiple inputs for checking
Last edited on
I forgot to mention that the program also shouldn't quit and should be able to accept multiple inputs for checking

So, put it in an input loop.
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

bool is_prime(int const n) {
  for (int i = 2; (i * i) <= n; ++i)  
    if (! (n % i)) return false;
  return true; 
}

int main() { 
  for (int input; (std::cin >> input) && input > 0; )    
    std::cout << input << " is" << (is_prime(input)? "": " not") << " prime.\n";    
}

http://coliru.stacked-crooked.com/a/1ec930001f88fb49
Last edited on
Topic archived. No new replies allowed.