Check a Prime Number
A prime number is greater than one and has no positive divisor other than one and itself.
What is Check a Prime Number?
A prime number is greater than one and has no positive divisor other than one and itself.
Determine whether an integer is prime.
Important points
- Compile with warnings enabled and fix every warning.
- Know the lifetime and type of every value.
- Validate input and keep array bounds explicit.
C and C++ code examples
main.c
#include <stdio.h>
int main(void) {
int number = 29, prime = number > 1;
// A composite number has a factor no larger than its square root.
for (int divisor = 2; divisor * divisor <= number; ++divisor)
if (number % divisor == 0) { prime = 0; break; }
printf("%d is %sprime\n", number, prime ? "" : "not ");
}
29 is prime
C++
main.cpp
#include <iostream>
int main() {
int number = 29;
bool prime = number > 1;
// Stop after the square root and on the first divisor.
for (int divisor = 2; divisor * divisor <= number && prime; ++divisor)
prime = number % divisor != 0;
std::cout << number << " is " << (prime ? "" : "not ") << "prime\n";
}
29 is prime
C and C++ comparison
Testing divisors while divisor squared is at most the number avoids unnecessary checks.
C
C exposes small procedural APIs and makes representation details explicit.
C++
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.