Bellow program will check the entered number by the user is whether a number is a Prime number or Not a Prime number by using the C++. I assume you have basic knowledge of C++ and C++ if, if…else and Nested if…else.
A prime number is a number which is exactly two positive divisors, 1 and the number itself, like if the user entered 13, then the entered number is a prime number. Below are the prime numbers between 1 to 100, which are only divisible by itself only.
1 | 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, and 97. |
Check if the entered number by the user is only divisible by 1 or itself, then it is a prime number. In this program we used the for()
loop and IF…ELSE statement. See the below example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <iostream> using namespace std; int main() { int n, i; bool isPrime = true; cout << "Enter a positive integer: "; cin >> n; for(i = 2; i <= n / 2; ++i) { if(n % i == 0) { isPrime = false; break; } } if (isPrime) cout << "This is a prime number"; else cout << "This is not a prime number"; return 0; } |
First run:
Enter an integer number: 115
115 is not a prime number
*********************************
Second run:
Enter an integer number: 13
13 is a prime number
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: C++ program to check prime number, how to check the number is prime number, prime number program in cpp, what is prime number