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).
Logic Tip:
Remember that 1 is not a prime number. Your function should handle cases where the input is less than or equal to 1 before entering the main loop.
Objective
- 1. Create
bool isPrime(int n)function. - 2. Return
falseimmediately for numbers ≤ 1. - 3. Use a
forloop andsqrt()for efficiency. - 4. Call the function from
main()and output a readable result.
Example C++ Exercise
#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:
7 is a prime number.
Enter a number: 12
12 is not a prime number.