Write the C++ program to check prime number
Copy the following code into the main.cpp
file:
#include <iostream>
using namespace std;
int main() {
int n, i;
bool isPrime = true;
// Get the number from the user
cout << "Enter a positive integer: ";
cin >> n;
// Check whether the number is prime
for(i=2; i<=n/2; i++) {
if(n%i == 0) {
isPrime = false;
break;
}
}
if(isPrime) {
cout << n << " is a prime number." << endl;
} else {
cout << n << " is not a prime number." << endl;
}
return 0;
}
This program takes an integer n
from the user and checks whether it is prime or not. If it's prime, print n is a prime number.
; otherwise, print n is not a prime number
.