A prime number is a natural number greater than 1 that has exactly two positive divisors: 1 and itself. This article explains different approaches to check whether a given number is prime in C.
- The brute-force approach checks all possible divisors.
- The optimized approach checks divisors only up to the square root of the number.
Illustration
Input: n = 29
Output: 29 is Prime
Explanation: 29 has no divisors other than 1 and 29 itself. Hence, it is a prime number.Input: n = 15
Output: 15 is NOT prime
Explanation: 15 has divisors other than 1 and 15 (i.e., 3 and 5). Hence, it is not a prime number.
Approaches to Check Whether a Number is Prime
There are two common approaches:
1. Brute Force Method
The brute-force approach checks every number from 1 to n and counts the divisors. A number is prime if it has exactly two divisors.
#include <stdio.h>
int main() {
int n = 29;
int count = 0;
if (n <= 1) {
printf("%d is NOT prime", n);
}
else {
for (int i = 1; i <= n; i++) {
if (n % i == 0)
count++;
}
if (count == 2)
printf("%d is prime", n);
else
printf("%d is NOT prime", n);
}
return 0;
}
Output
29 is prime
Explanation: The program checks every number from 1 to n. If exactly two numbers divide n, the number is prime.
2. Optimized Method
A number is composite if it has a factor less than or equal to its square root. Therefore, instead of checking all numbers up to n, we only check divisors up to √n.
#include <stdio.h>
int main() {
int n = 29;
int isPrime = 1;
if (n <= 1) {
isPrime = 0;
}
else {
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
isPrime = 0;
break;
}
}
}
if (isPrime)
printf("%d is prime", n);
else
printf("%d is NOT prime", n);
return 0;
}
Output
29 is prime
Explanation: The loop checks possible divisors only up to √n. If any divisor is found, the number is not prime; otherwise, it is prime.
Further Optimization by Skipping Even Numbers
The optimized approach can be improved slightly by handling 2 separately and checking only odd divisors from 3 to √n.
#include <stdio.h>
int main() {
int n = 29;
int isPrime = 1;
if (n <= 1)
isPrime = 0;
else if (n == 2)
isPrime = 1;
else if (n % 2 == 0)
isPrime = 0;
else {
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
isPrime = 0;
break;
}
}
}
if (isPrime)
printf("%d is prime", n);
else
printf("%d is NOT prime", n);
return 0;
}
Output
29 is prime
Explanation: Since 2 is the only even prime number, all even numbers greater than 2 can be rejected immediately. The program then checks only odd divisors up to √n.