-1

I'm trying to do this :

  1. The User chooses one number
  2. The program calls the 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));

}
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Amat Erasu
  • 73
  • 5

3 Answers3

2

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;
}
Cloud
  • 18,753
  • 15
  • 79
  • 153
0

If you delete the do loop your code will work. This is because your loop will run as long as the isprime returns true, and will stop running when isprime returns false.

Also if you want to display whether or not the number is prime you should use cout << isPrime(p);

thus your main funcion should look like

int main()
{
  int p;
  cout << "p : ";
  cin >> p;
  cout << isPrime(p);
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Erk
  • 41
  • 6
0

According to your question: When user chooses a non prime number the loop iterates. What you are doing is reverse so just replace

else{
bool prime =false   //replaced to true
//your code
while (divisor <= upperLimit)
    {
        if (num % divisor == 0)
            {
                prime = true;   //replaced to true 
                break;
            }
        divisor +=2;
    }
    return prime;
wrangler
  • 3,454
  • 1
  • 19
  • 28