C++ Program to Check Whether a Number is Prime or Not

What Is Prime Number

A prime number is a positive integer that is exactly divisible by the 1 and the number itself.

1, 3, 5, 7, 11, 17, 19 are the examples of prime numbers from 1 to 20

Example Prime Number

For example, 3 is a prime number because it is only divisible by 1 and 3, also 7 is a prime number because it is only divisible by 1 and the number itself 7.

So, 27 is not a prime number because it is divisible by 1, 3, 9, and 27.

Ad

MCQ: 2 is the only even number which is a prime number.

Related: C++ Program Factorial of a Number

C++ Program Prime Number 1

#include <iostream> using namespace std; int main() { int i, n; bool isPrime = true; cout << "Enter a positive integer: "; cin >> n; // 0 and 1 are not prime numbers if (n == 0 || n == 1) { isPrime = false; } else { // 2 is a prime number for (i = 2; i <= n / 2; ++i) { if (n % i == 0) { isPrime = false; break; } } } if (isPrime) cout << n << " is a prime number"; else cout << n << " is not a prime number"; return 0; }
Code language: PHP (php)

Also Read: C++ Program Factorial using Recursion

Prime Number C++ Program 2

//C++ program to check for prime number #include<iostream> using namespace std; int main() { int num, i, j = 0; cout << "Enter number: "; cin >> num; //check for prime number for (i = 1; i <= num; i++) { if ((num % i) == 0) { j++; } } if (j == 2) cout << "\n" << num << " is a prime number.\n"; else cout << num << " is not a prime number.\n"; return 0; }
Code language: PHP (php)
Ad