check_prime.cpp (checks if input is a prime number) check_prime.cpp

Description: Accepts user input to check if the user entered a prime number.

Notes: If any text inputted after an integer will be ignored. 

For example: 1234.5678 and 98abc will be interpreted as 1234 and 98, respectively.

Please provide any feedback (positive or negative).  

// check_prime.cpp
// Author: Chris Heath
// Date: 12/9/2018
// Description: Accepts user input to check if the user entered a prime number.
// Notes: If any text inputted after an integer will be ignored.
// For example: 1234.5678 and 98abc will be interpreted as 1234 and 98, respectively.

#include &lt;iostream&gt;
#include &lt;string&gt;
#include &lt;limits&gt;

using namespace std;

int is_prime (unsigned long int num)
{
    unsigned long int n;
    // avoid loop;  0 or 1 are never prime
    if (num == 0 || num == 1)
        return 0;
    // loop through numbers 0..(n/2)+1, trying to
    // divide one into the other with no remainder.
    for (n=2; n &lt; (num/2)+1; n++)
    {
        // if we had no remainder during a revision,
        // input number has a divisor... NOT PRIME!
        if ((num % n) == 0)
          return 0;
    }
    // made it through gauntlet...prime!
    return 1;
}

int main()
{
 unsigned long int i;
 cout&lt;&lt;"Enter an integer to check if it is a prime: ";
 cin&gt;&gt;i;
 while(1)
 {
  if(cin.fail())
  {
   cin.clear();
   cin.ignore(numeric_limits&lt;streamsize&gt;::max(),'\n');
   cout&lt;&lt;"You have entered wrong input.\nPlease try again: ";
   cin&gt;&gt;i;
  }
  if(!cin.fail())
  break;
 }
 if ( is_prime(i) )
  cout&lt;&lt;"\n"&lt;&lt;i&lt;&lt;" IS PRIME!"&lt;&lt;endl;
 else
  cout&lt;&lt;"\n"&lt;&lt;i&lt;&lt;" is NOT prime."&lt;&lt;endl;
return 0;
}
Don't use using namespace std;.

Since is_prime only has two possible return values, and given its name implies a binary result, it should return a bool, not an int.  Then replace the return statements with the proper bool values.

When checking for primes, you only need to go up to the square root of the number to check.  This value can be computed once then used in the loop condition, or you can check for i * i &lt;= num, although this has the potential to overflow with sufficiently large num.

The check for 0 or 1 can be simplified to if (num &lt; 2).

Before the loop, you can check num to see if it is divisible by 2 and return an appropriate value.  Then you loop can start at 3 and increment by 2 (so you only need to check the odd numbers).

You should declare your variables as close to the place you first use them as possible, so your loop could be

for (unsigned long n = 3; ...


(or for (auto n = 3UL;).

When getting input, rather than while (1) with repeated conditions in the loop, you can say while (!cin.fail()) and not check for that within the loop.