Question #43475

write a function to check whether the number entered by a user is a prime number

Expert's answer

`#include <iostream>`

bool isPrime(int n) {

if ( n <= 1 ) {

return false;

}

for ( int i = 2; i <= n / 2; i++ ) {

if ( n % i == 0 ) {

return false;

}

}

return true;

}

int main() {

int number, input;

while ( true ) {

std::cout << "Please enter the number to be checked for being prime" << std::endl;

std::cin >> number;

if ( isPrime(number) ) {

std::cout << "Prime" <<std::endl;

} else {

std::cout << "Not prime" << std::endl;

}

std::cout << "Another check? 0 for no" << std::endl;

std::cin >> input;

if (! input ) {

break;

}

}

}

## Comments

## Leave a comment