Check if a Number is Prime Using a Boolean Function

Check if a Number is Prime Using a Function

This exercise combines number theory with modular programming. You will implement a function that determines if a number is prime (a natural number greater than 1 that has no positive divisors other than 1 and itself). This is a classic algorithm to practice efficiency and boolean logic in C++.

Technical Components

1. Boolean Function

Using bool as a return type is ideal for "yes/no" questions like checking primality.

2. Loop Optimization

Iterating only up to sqrt(n) significantly improves performance for large numbers.

3. Modulo Operator

The % operator is used to check if the remainder of a division is zero (indicating a divisor).

Objective

  • 1. Create bool isPrime(int n) function.
  • 2. Return false immediately for numbers ≤ 1.
  • 3. Use a for loop and sqrt() for efficiency.
  • 4. Call the function from main() and output a readable result.

Example C++ Exercise

prime_check.cpp Functions
#include <iostream>
#include <cmath>

using namespace std;

// Function to check if a number is prime
bool isPrime(int number) {
    if (number <= 1) return false;

    // Check from 2 to square root of number
    for (int i = 2; i <= sqrt(number); i++) {
        if (number % i == 0) {
            return false; // Found a divisor
        }
    }
    return true; // No divisors found
}

int main() {
    int num;

    cout << "Enter a number: ";
    cin >> num;

    if (isPrime(num)) {
        cout << num << " is a prime number." << endl;
    } else {
        cout << num << " is not a prime number." << endl;
    }

    return 0;
}

Sample Output:

Enter a number: 7
7 is a prime number.

Enter a number: 12
12 is not a prime number.
Related Concepts
Boolean Functions Algorithm Optimization Primality Test cmath Library

Share this C++ Exercise

Found this helpful? Share it with your fellow developers!

© C++ Programming Exercises. Master the art of performance coding.