Write a c++ program code that enters a number and prints wether or not it is prime number?
#include <iostream>
using namespace std;
bool is_prime(unsigned x) {
if (x <= 1)
return false;
if (x == 2)
return true;
if (x % 2 == 0)
return false;
unsigned n = 3;
while (n*n <= x) {
if (x % n == 0)
return false;
n += 2;
}
return true;
}
int main() {
unsigned x;
cout << "Enter a positive integer: ";
cin >> x;
if (is_prime(x))
cout << "It is a prime number" << endl;
else
cout << "It is not a prime number" << endl;
return 0;
}
Comments
Leave a comment