Program to Check if a Number is Prime in C++
Checking Prime Number
A prime number is a natural number greater than 1 that has no divisors other than 1 and itself.
We will explore different methods to check if a number is prime using C++ programming.
Method 1: Using a for Loop
We iterate from 2 to the square root of the number and check for divisibility.
#include <iostream> using namespace std; int main() { int num, i; bool isPrime = true; cout << "Enter a number: "; cin >> num; if (num < 2) { isPrime = false; } else { for (i = 2; i * i <= num; i++) { if (num % i == 0) { isPrime = false; break; } } } if (isPrime) cout << num << " is a prime number"; else cout << num << " is not a prime number"; return 0; }
Output:
Enter a number: 7 7 is a prime number
Method 2: Using a Function
We create a function to check for primality and return the result.
#include <iostream> using namespace std; bool isPrime(int num) { if (num < 2) return false; for (int i = 2; i * i <= num; i++) { if (num % i == 0) return false; } return true; } int main() { int num; cout << "Enter a number: "; cin >> num; if (isPrime(num)) cout << num << " is a prime number"; else cout << num << " is not a prime number"; return 0; }
Output:
Enter a number: 10 10 is not a prime number