C++ Program: Check if a Number is Prime
Program Code:
#include <iostream>
#include <cmath> // For sqrt function
using namespace std;
// Function to check if a number is prime
bool isPrime(int n) {
// Corner cases
if (n <= 1) {
return false;
}
if (n <= 3) {
return true;
}
// Check for divisibility from 2 to sqrt(n)
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
// Check if number is prime and display result
if (isPrime(number)) {
cout << number << " is a prime number." << endl;
} else {
cout << number << " is not a prime number." << endl;
}
return 0;
}
Explanation of the Program
- Function
isPrime
:bool isPrime(int n)
: This function takes an integern
as input and returnstrue
ifn
is a prime number, andfalse
otherwise.- Edge Cases: Numbers less than or equal to 1 (
n <= 1
) are not prime. - Optimization: For numbers greater than 1, the function checks divisibility from 2 up to the square root of
n
(sqrt(n)
). This optimization reduces the number of checks needed.
- Main Function:
- Prompts the user to enter a number.
- Calls the
isPrime
function to check if the entered number is prime. - Displays the result based on the return value of
isPrime
.