Write a program in C++ that ask the user to type a value and check whether it is prime or not.
#include <iostream>
using namespace std;
bool is_prime(int x) {
if (x <=1 ) {
return false;
}
if (x == 2) {
return true;
}
if (x % 2 == 0) {
return false;
}
int i = 3;
while (i*i <= x) {
if (x % i == 0) {
return false;
}
i += 2;
}
return true;
}
int main() {
int n;
cout << "Enter a positive number: ";
cin >> n;
if (is_prime(n)) {
cout << n << " ia a prime number" << endl;
}
else {
cout << n << " is not a prime number" << endl;
}
return 0;
}
Comments
Leave a comment