C++: How to Check Whether a Number is a Prime Number (Source Code)

Read this article now to find out how to check whether a given number is a prime number using a self-written C++ program. (With Source Code)
C++ check whether a number is a prime number thumbnail

What is a prime number?

A prime number is any number greater than one, which is dividable only by itself or by one. (e. g. 7)
1 and 0 aren’t prime numbers because a prime number must be dividable by two different numbers and because you can’t divide by 0.

Here are the first ten prime numbers:
2; 3; 5; 7; 11; 13; 17; 19; 23; 29 . . . (list of prime numbers up to 10,000)

Keep in mind that 2 is the only even prime number. If a different number is even, hence dividable by two, it is never a prime number.

At some point, it gets really hard to figure out whether a number is a prime number on your own. Therefore, keep reading to find out how to check whether a number is a prime number using a simple C++ code!

Check for Given Numbers

Luckily, checking if a given number is a prime number is very easy and doesn’t require complicated explanations.

Here’s the code for a standalone console application:

				#include <iostream>

using namespace std;

int main() {

    unsigned long long n, i;
    bool prime = true;

    cout << "Please provide a positive integer: ";
    cin >> n;

    // If the number is smaller or equal to one, it is no prime number
    if (n <= 1) {
        prime = false;
    }
    else {
        // Check if the given number is a prime number
        for (i = 2; i <= n/2; i++) { // We divide the given number by 2 to reduce processing time
            if (n % i == 0) { // If n is dividable by a number other than 1 or n it is not a prime number
                prime = false;
                break;
            }
        }
    }

    if (prime)
        cout << n << " is a prime number";
    else
        cout << n << " is not a prime number -> Dividable by " << i;

    return 0;
}
			

If you plan to use this code in your project, you should make sure that the program can handle invalid user input. For example, if the user enters a negative number or no number at all.

As you probably know, you can handle invalid user inputs using a try-catch statement around the first if-else statement.

 

If you just want a simple function without console input and output, you can use this bit of code:

				bool is_prime(unsigned long long n) {
    if (n <= 1) { 
        return false;
    }
    else {
        for (unsigned long long i = 2; i <= n/2; i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }
}
			

When using this snippet of code in your project, be aware that checking for larger numbers takes a while and can “freeze” your program if you don’t offload this task to another thread.

Automatically Search for Prime Numbers

Of course, there also is a very simple code snippet to automatically search for prime numbers and store them in a vector.

Here you have a function you can include in your projects:

				#include <vector>

std::vector<unsigned long long> search(unsigned long long max = 1000) {
    std::vector<unsigned long long> primes;

    for (int x = 2; x <= limit; x++) { // Check all numbers above one and under or equal to the maximum
        bool prime = true;
        for (int i = 2; i <= x/2; i++) { // Check if x is a prime number
            if (x % i == 0) {
                prime = false;
                break;
            }
        }
        if (prime) { // If a prime number has been found, add it to the vector
            primes.push_back(x);
        }
    }

    //for (auto e : primes) // print the results
    //    cout << e << "\n";

    return primes;
}
			

How it works:
We specify a maximum number (default: 1,000), iterate from 2 to the maximum, check each number if it is a prime number, and if it is, we add the number to a primes vector. Finally, we can return the vector and print all the prime numbers that were found.

Thanks for reading!

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *