I'm trying to do this :
isaPrime()
function so we see if number is prime or not.I wanted to do a loop so every time the number is not a prime, the user has to choose a new value.
Here's the code:
#include <iostream>
#include <math.h>
using namespace std;
bool isPrime (int num)
{
if (num <=1)
return false;
else if (num == 2)
return true;
else if (num % 2 == 0)
return false;
else
{
bool prime = true;
int divisor = 3;
double num_d = static_cast<double>(num);
int upperLimit = static_cast<int>(sqrt(num_d) +1);
while (divisor <= upperLimit)
{
if (num % divisor == 0)
prime = false;
divisor +=2;
}
return prime;
}
}
int main()
{
int p;
do {
cout << "p : ";
cin >> p;
isPrime(p);
} while (isPrime(p));
}
This should handle your user I/O loop. You just need to replace the isPrime
function with your own implementation.
Code Listing
#include <iostream>
#include <iomanip>
#define isPrime(x) (1)
int main(void)
{
using namespace std;
const int maxchar = 5;
string nationname;
int input;
int running = 1;
while ( running )
{
cout << "Enter a number:";
cin >> input;
if ( isPrime(input ) )
{
// Do something
running = 0;
}
else
{
cout << "Not a prime number. Please try again!" << endl;
}
}
return 0;
}