find prime number c++
To find prime numbers in C++, you can follow these steps:
Start by defining a function named
isPrime
that takes an integer parameternum
and returns a boolean value. This function will check if the given number is prime or not.Inside the
isPrime
function, handle the base cases. Ifnum
is less than or equal to 1, returnfalse
as prime numbers are greater than 1. Ifnum
is 2, returntrue
as it is the only even prime number.Use a loop to iterate from 2 to the square root of
num
. For each iteration, check ifnum
is divisible by the current iteration value. If it is, returnfalse
as it is not a prime number.If the loop completes without finding any divisors, return
true
as the number is prime.In your main function, prompt the user to enter a number to check if it is prime.
Read the input number using
cin
.Call the
isPrime
function with the input number as the argument.Print a message indicating whether the number is prime or not based on the returned boolean value of the
isPrime
function.
Here's an example implementation:
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int num) {
if (num <= 1) {
return false;
}
if (num == 2) {
return true;
}
for (int i = 2; i <= sqrt(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 defines a function isPrime
that checks if a number is prime or not. In the main
function, a number is read from the user and passed to the isPrime
function. The result is then printed based on the returned boolean value.