prime number in c++
C++ Code to Check Prime Numbers
#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";
} else {
cout << number << " is not a prime number";
}
return 0;
}
- Include the necessary header files.
- Define a function named
isPrime
that takes an integer parameter. - Check if the number is less than or equal to 1, and return false if true.
- Iterate through the numbers from 2 to the square root of the input number.
- Check if the input number is divisible by the current iteration number, and return false if true.
- Return true if the input number passes the above conditions.
- In the
main
function, prompt the user to enter a number. - Read the input number from the user.
- Call the
isPrime
function and display whether the input number is prime or not.