Introduction
A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.
In other words, a prime number is only divisible by 1 and itself. The objective of this program is to check if a given
number is prime or not using C++ programming.
Objective
The primary goal of this program is to determine whether a given integer is prime or not. The program will:
- Take an integer as input from the user.
- Check if the number is divisible by any number other than 1 and itself.
- Return a result indicating whether the number is prime or not.
Code
#include using namespace std; // Function to check if a number is prime bool isPrime(int number) { // A number less than 2 is not prime if (number <= 1) { return false; } // Check divisibility up to the square root of the number for (int i = 2; i * i <= number; i++) { if (number % i == 0) { return false; // Divisible by i, so it's not prime } } return true; // Number is prime if no divisors were found } int main() { int num; // Ask the user to input a number cout << "Enter a number: "; cin >> num; // Check if the number is prime if (isPrime(num)) { cout << num << " is a prime number." << endl; } else { cout << num << " is not a prime number." << endl; } return 0; }
Explanation of the Program
This C++ program checks whether a given number is prime using the following steps:
- The program defines a function
isPrime(int number)
that takes an integer as input and checks whether the number is prime. - If the number is less than or equal to 1, it immediately returns
false
because numbers less than or equal to 1 are not prime. - The program uses a
for
loop to check divisibility from 2 up to the square root of the number. This is an optimization that reduces the number of checks needed. - If the number is divisible by any number in this range, the function returns
false
, indicating the number is not prime. - If no divisors are found, the function returns
true
, indicating the number is prime. - In the
main
function, the program prompts the user to enter a number, calls theisPrime
function, and prints the result accordingly.
How to Run the Program
To run the C++ program, follow these steps:
- Open a text editor (e.g., Notepad++ or Visual Studio Code) and paste the above code into a new file.
- Save the file with a
.cpp
extension (e.g.,prime_checker.cpp
). - Open a terminal or command prompt and navigate to the directory where the file is saved.
- Compile the program using a C++ compiler. For example, if you’re using
g++
, type the following command:g++ -o prime_checker prime_checker.cpp
- Run the compiled program with this command:
./prime_checker
- Enter an integer when prompted, and the program will tell you whether it is prime or not.