-5

The question is:

"Create a program that asks the user to enter any integer, and then indicates to the user if the number entered was prime or not. Do this by creating a C++ function whose input is any integer; by counting the number of factors, your function should return true if the input is prime, and false otherwise."

Here's my code (please give direction not a precise answer):

using namespace std;

int i;

bool isPrime (int x)

    {
        if (x%i == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }


int main()

{

    for (int i = 2; i < x; i++)

    {

    }
}

Thanks!

2 Answers2

3

A very quick and simple primality test which is straightforward and correct, but not efficient for large primes.

bool isPrime(int x){

    if(x < 2) return false;
    if(x == 2) return true;
    if(x % 2 == 0) return false;

    for(int i=3; (i*i) <= x; i+=2){
        if(x % i == 0 ) return false;
    }
    return true;
}

REF: Determining if a number is prime

There are many ways to ask the user for an integer input and report back if it is prime or not, but this is main method you are looking for.

Community
  • 1
  • 1
Drakes
  • 23,254
  • 3
  • 51
  • 94
0
#include <iostream>
using namespace std;

bool isPrime(int x)
{
    for(int i = 2; i <= x/2; i++)
        if(x%i ==0)
            return false;
    return true;
}
int main()
{
    int x;
    cout<<"Enter a number: ";
    cin>>x;

    isPrime(x) ? cout<<x<<" is prime" : cout<<x<<" is not prime"<<endl;

    return 0;
}