Prime Number Checker
#include <iostream>
using namespace std;
bool isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
if (isPrime(number)) {
cout << number << " is a prime number." << endl;
} else {
cout << number << " is not a prime number." << endl;
}
return 0;
}
This code includes the necessary header files and defines a function isPrime
to check if a given number is prime. The function takes an integer as input and returns a boolean value (true
if the number is prime and false
otherwise).
isPrime
function:- It checks if the input number is less than or equal to 1, returning
false
in such cases. - It iterates from 2 up to the square root of the input number.
- Inside the loop, it checks if the number is divisible by
i
. If it is, the number is not prime andfalse
is returned. If no divisors are found within the loop, the function returns
true
, indicating the number is prime.main
function:- It prompts the user to enter a number.
- Reads the input number using
cin
. - Calls the
isPrime
function with the entered number. - Prints a message stating whether the number is prime or not based on the returned value from
isPrime
.
The code utilizes a basic prime number checking algorithm that iterates up to the square root of the number to determine its primality, efficiently avoiding unnecessary iterations beyond that point.