A prime number can be defined as a number that is only divisible by 1 and by itself.
- 2 is the only even prime number.
- 1 is not considered a prime number.
In this shot, we will learn how to check if a number is prime or not in C++. For this, we will use a for
loop and check some conditions in the loop.
The loop will execute until the condition becomes false
.
After that, the loop will terminate and we will get our output for the given number.
Let’s clarify this concept with the following code snippet.
#include <iostream>using namespace std;int main(){int number, i, isPrime = 1;cin >> number;if (number <= 1)isPrime = 0;for ( i = 2 ; i <= number/2 ; i++){if (number % i == 0){isPrime = 0;break;}}if (isPrime == 1)cout << "The number is a prime number." ;elsecout << "The number is not a prime number." ;return 0;}
Enter the input below
Enter a value to be tested above to check if it is prime or not.
In line 6, we initialize the number
, i
, and isPrime
variables. We initialize the value of isPrime
to be 1, that is, the number is prime.
In line 9, we check if the given number is less than 1. If so, then we set the isPrime
variable to 0, which means the number is not prime. Otherwise, we move forward.
In line 12, we use a for
loop, where the loop will run from 2 to the half of the number.
In line 14, we divide the number with every value of i
. If the remainder becomes 0, the number is prime, the loop gets terminated, and the program will end. Otherwise, it will run the loop again until we met the condition.
In line 21, we print the number is a prime number
if the value of isPrime == 1
; otherwise, in line 23, we print the number is not a prime number
.
In this way, we can easily check if a given number is prime or not.