In C++, a prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself.
In this tutorial, we will discuss how to check whether a given number is prime or not in C++.
To check whether a given number is prime or not, we can use the following algorithm:
- Check if the number is less than 2, if yes, then it is not a prime number.
- If the number is greater than or equal to 2, then loop from 2 to the square root of the given number. If the given number is divisible by any number between 2 and the square root of the number, then it is not a prime number.
- If the given number is not divisible by any number between 2 and the square root of the number, then it is a prime number.
Here is the C++ code that implements the above algorithm:
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int n) {
if (n < 2) {
return false;
}
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
if (isPrime(n)) {
cout << n << " is a prime number." << endl;
} else {
cout << n << " is not a prime number." << endl;
}
return 0;
}
In the above code, the function isPrime takes an integer argument n and returns a boolean value indicating whether n is a prime number or not.
The function first checks if the number is less than 2. If yes, then it returns false as the number is not a prime number.
If the number is greater than or equal to 2, then it loops from 2 to the square root of the given number and checks if the number is divisible by any number in the range.
If the number is divisible by any number in the range, then it returns false as the number is not a prime number.
If the number is not divisible by any number in the range, then it returns true as the number is a prime number.
In the main function, we take an integer input from the user and call the isPrime function to check if the number is prime or not.
If the number is prime, we print a message indicating that the number is a prime number. Otherwise, we print a message indicating that the number is not a prime number.
In conclusion, the above C++ code can be used to check whether a given number is prime or not using a simple algorithm.




