Back to C++
2026-03-125 min read

Check Whether a Number is Prime or Not (C++)

Learn Check Whether a Number is Prime or Not (C++) step by step with clear examples and exercises.

Why This Matters

In this extensive C++ lesson, we will delve into the intricacies of creating a program that checks whether a given number is prime or not. Learning how to write such a program is crucial for various competitive programming problems and can also be beneficial when validating user input in your applications.

Why This Matters

Prime numbers play a significant role in mathematics, cryptography, and computer science. A prime number is an integer greater than 1 that has no divisors other than 1 and itself. For instance, the first six prime numbers are 2, 3, 5, 7, 11, and 13. Checking whether a number is prime or not is an essential problem in computer science due to its frequent appearance in various algorithms and mathematical problems.

Prerequisites

To fully grasp this lesson, you should have a solid understanding of the following C++ programming concepts:

  • Basic C++ syntax (variables, operators, control structures)
  • Functions (defining and calling functions)
  • Loops (for loops, while loops, and do-while loops)
  • Conditional statements (if-else statements)
  • Arrays
  • Standard Template Library (STL) concepts such as vectors and iterators

Core Concept

The trial division method is the simplest algorithm to check whether a number is prime or not. This algorithm checks divisibility from 2 up to the square root of the given number. If no divisor is found, then the number is prime.

Here's an enhanced implementation of this algorithm in C++:

#include <iostream>
#include <vector>
using namespace std;

bool isPrime(int n) {
vector<bool> divisors(n + 1, true); // initialize all numbers as prime
for (int i = 2; i <= sqrt(n); ++i) {
if (divisors[i]) {
for (int j = i * i; j <= n; j += i) {
divisors[j] = false; // mark non-prime numbers as composite
}
}
}
return divisors[n]; // the number is prime if it remains marked as such in the vector
}

int main() {
int num;
cout << "Enter a positive integer: ";
cin >> num;
if (isPrime(num)) {
cout << num << " is a prime number." << endl;
} else {
cout << num << " is not a prime number." << endl;
}
return 0;
}

In the code above, we define a function isPrime(int n) that takes an integer as input and returns true if the number is prime and false otherwise. The function uses a vector to keep track of all numbers up to n and their primality status. Initially, all numbers are marked as prime (true). Then, we iterate through possible divisors from 2 up to the square root of the given number and mark their multiples as composite (false) in the vector. If a number remains marked as true in the vector, it is prime.

In the main() function, we ask the user for input, call the isPrime() function with the user's input, and display the result.

Worked Example

Let's test our program with a few examples:

  1. Input: 2

Output: 2 is a prime number.

  1. Input: 4

Output: 4 is not a prime number.

  1. Input: 17

Output: 17 is a prime number.

Common Mistakes

When implementing this algorithm, some common mistakes to avoid include:

Forgetting the base case (n <= 1)

If you forget to check for the base case, your function will incorrectly classify all numbers as prime, including 0 and 1.

Checking divisibility up to the number itself instead of its square root

Checking divisibility up to the number itself instead of its square root can lead to an inefficient algorithm. For example, checking whether 2,345,678 is prime would require checking divisibility by every number from 2 to 2,345,678, which is not practical.

Not handling negative numbers correctly

The trial division method only works for positive integers, so you should ensure that your function accepts only positive integers as input and handles negative numbers appropriately (e.g., by returning an error message).

Not optimizing the algorithm for large numbers

For large numbers, using a vector to store the primality status of all numbers can be inefficient. In such cases, you should consider using more advanced algorithms like the Sieve of Eratosthenes or other primality testing methods.

Practice Questions

  1. Modify the isPrime() function to return the smallest prime factor of a given number instead of just checking whether it's prime or not.
  2. Implement an optimized algorithm for checking whether a number is prime using the Sieve of Eratosthenes.
  3. Write a C++ program that generates all prime numbers up to a given limit and stores them in a vector for future use.
  4. Research and implement other algorithms for checking prime numbers, such as the Miller-Rabin primality test or the AKS primality test.
  5. Create a function that checks whether a number is a Mersenne prime (a prime number of the form 2^n - 1).
  6. Write a program that finds the largest prime factor of a given composite number.
  7. Implement a function that generates all prime numbers up to a given limit using the Sieve of Eratosthenes and stores them in an array.
  8. Research and implement a primality testing method based on elliptic curves.

FAQ

Q: Why do we stop at the square root when checking divisibility?

A: We stop at the square root because any factor greater than the square root of the number would have a corresponding factor less than or equal to the square root (e.g., if 10 is divisible by 5, then it's also divisible by 2 and 5/2 = sqrt(10)).

Q: What are some other algorithms for checking prime numbers?

A: In addition to the trial division method, there are several other algorithms for checking prime numbers, such as the Miller-Rabin primality test, AKS primality test, and the Fermat primality test. These algorithms are more efficient than the trial division method for large numbers but are generally more complex to implement.

Q: Why do we exclude 0 and 1 from being prime numbers?

A: By convention, mathematicians define a prime number as a positive integer greater than 1 that has no divisors other than 1 and itself. Since 0 has no divisors at all (only multiples), it is not considered a prime number. Similarly, 1 can be divided by any number (including itself), so it's also excluded from the definition of prime numbers.

Q: What are Mersenne primes?

A: A Mersenne prime is a prime number of the form 2^n - 1, where n is a positive integer. Examples include 3 (2^2 - 1), 7 (2^3 - 1), and 31 (2^5 - 1). Mersenne primes have practical applications in cryptography and computer science.

Q: What are the largest known prime numbers?

A: The largest known prime number is 2^82,589,933 - 1, discovered in 2018. It has 24,862,048 digits and was found using the Great Internet Mersenne Prime Search (GIMPS).

Q: What is the Riemann Hypothesis?

A: The Riemann Hypothesis is a famous conjecture in number theory that states that all non-trivial zeros of the Riemann zeta function lie on the critical line. This hypothesis has important implications for prime number theory and has been unsolved since its formulation in 1859. If proven, it could lead to significant advancements in our understanding of prime numbers.

Check Whether a Number is Prime or Not (C++) | C++ | XQA Learn