check prime cpp gfg
The C++ code below checks whether a given number is prime or not. Each step is explained to provide a better understanding of the code:
#include <iostream>
using namespace std;
bool isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (isPrime(num)) {
cout << num << " is a prime number." << endl;
} else {
cout << num << " is not a prime number." << endl;
}
return 0;
}
Explanation:
The code starts by including the
iostream
library, which is necessary for input and output operations.The
using namespace std;
line is used to avoid writingstd::
before standard library functions.The
isPrime
function takes an integern
as input and returns a boolean value indicating whethern
is prime or not.The first condition in the
isPrime
function checks ifn
is less than or equal to 1. If it is, the function returnsfalse
because prime numbers are greater than 1.The
for
loop in theisPrime
function iterates fromi = 2
toi * i <= n
. This loop is used to check ifn
is divisible by any number between 2 and the square root ofn
. Ifn
is divisible by any number in this range, it meansn
is not prime, and the function returnsfalse
.If the
for
loop completes without finding any divisors forn
, it meansn
is prime, and the function returnstrue
.The
main
function is where the program execution starts.Inside the
main
function, an integer variablenum
is declared to store the user input.The
cout
statement is used to display the message "Enter a number: " to prompt the user to enter a number.The
cin
statement is used to read the user input and store it in thenum
variable.The
if
statement checks ifnum
is prime by calling theisPrime
function. If it returnstrue
, the message "num is a prime number." is displayed. Otherwise, the message "num is not a prime number." is displayed.Finally, the
return 0;
statement indicates that the program has executed successfully and returns the value 0 to the operating system.