Answer to Question #43475 in C++ for dharshana

Question #43475
write a function to check whether the number entered by a user is a prime number
1
Expert's answer
2014-06-19T12:46:36-0400
#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;
}
}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS