C language learning often introduces “prime number testing” as one of the basic problems. For programming beginners, it is a good opportunity to acquire the ability to understand the properties of numbers and choose appropriate algorithms. Also, by learning more efficient prime-testing algorithms, you deepen your understanding of differences in algorithmic complexity and program optimization. In this article, we will introduce methods for determining prime numbers using C and provide sample code that actually works. We will cover various techniques, from the basic trial division method to the faster Sieve of Eratosthenes.
2. What is a prime number?
Prime numbers are natural numbers that have no positive divisors other than 1 and themselves. For example, 2, 3, 5, 7, 11, etc., are prime numbers.
2.1. Basic characteristics of prime numbers
The smallest prime is 2 (the only even prime)
1 is not a prime (because it has only one divisor)
There are infinitely many primes
If an integer n ≥ 2 is not prime, it is always divisible by some prime ≥ 2
2.2. Concrete examples of primes
Number
Prime?
2
✅ Prime
3
✅ Prime
4
❌ Composite (2×2)
5
✅ Prime
6
❌ Composite (2×3)
7
✅ Prime
8
❌ Composite (2×4)
9
❌ Composite (3×3)
3. Basic Prime Checking Method in C (🔰 Beginner-friendly)
Here, we introduce the most basic method, the “Trial Division”.
3.1. Trial Division (Basic)
Trial division is a method that, for an integer N greater than or equal to 2, checks whether it can be divided evenly by any integer other than 1 and N itself.
If N is an integer ≥ 2, check whether it is divisible by any number from 2 to N‑1
If a divisor is found, it is a “composite number”; otherwise, it is a “prime number”
Sample Code (Basic Version)
#include <stdio.h>
int is_prime(int n) {
if (n < 2) return 0; // Numbers ≤ 1 are not prime
for (int i = 2; i < n; i++) { // Check divisibility from 2 up to n-1
if (n % i == 0) return 0;
}
return 1;
}
int main() {
int num = 7;
if (is_prime(num))
printf("%d is a prime numbern", num);
else
printf("%d is not a prime numbern", num);
return 0;
}
Output
7 is a prime number
This method is simple and easy to understand, but it has the drawback that its time complexity is O(N), so processing time grows long as N becomes large. The next section introduces a more efficient method.
4. Efficient Prime Number Detection in C (Sieve of Eratosthenes & Improved Trial Division)
To optimize prime detection calculations, we explain the following two methods.
Trial Division up to √N (Optimized)
Sieve of Eratosthenes
4.1. Trial Division up to √N (Optimized)
The point is that any non‑prime number N always has a divisor less than or equal to √N, so you only need to check up to the square root of N. Sample Code
#include <stdio.h>
#include <math.h>
int is_prime_optimized(int n) {
if (n < 2) return 0;
if (n % 2 == 0 && n != 2) return 0; // Even numbers other than 2 are not prime
for (int i = 3; i <= sqrt(n); i += 2) { // Check only odd numbers (skip even)
if (n % i == 0) return 0;
}
return 1;
}
int main() {
int num = 29;
if (is_prime_optimized(num))
printf("%d is a prime numbern", num);
else
printf("%d is not a prime numbern", num);
return 0;
}
Output
29 is a prime number
With this method, the time complexity improves from O(N) → O(√N), allowing fast determination even for large numbers.
4.2. Sieve of Eratosthenes
The Sieve of Eratosthenes is an algorithm that efficiently finds primes by eliminating multiples of small prime numbers.
Start with 2 and eliminate all its multiples
Then eliminate multiples of the next smallest remaining number (3)
Repeating this process leaves only prime numbers
Sample Code
#include <stdio.h>
#include <stdbool.h>
void sieve(int n) {
bool prime[n + 1];
for (int i = 0; i <= n; i++) prime[i] = true;
for (int p = 2; p * p <= n; p++) {
if (prime[p]) {
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
for (int p = 2; p <= n; p++)
if (prime[p])
printf("%d ", p);
printf("n");
}
int main() {
int n = 50;
sieve(n);
return 0;
}
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
The time complexity of the Sieve of Eratosthenes is O(N log log N), making it optimal for generating large quantities of prime numbers.
5. Performance Comparison of Prime-Testing Algorithms in C (Speed Measurement and Optimization)
There are several different methods for prime testing algorithms, and their processing speed and efficiency vary greatly. In this section, we measure execution time in C for the following three methods and discuss which method is effective in which scenarios.
Trial division (basic): O(N)
Trial division up to √N (optimized): O(√N)
Sieve of Eratosthenes (when finding primes within a range): O(N log log N)
5.1. How to Measure Execution Time
In C, you can use the clock() function to measure processing time. Sample code for basic execution time measurement
#include <stdio.h>
#include <time.h>
void measure_time(void (*func)(int), int n) {
clock_t start, end;
start = clock(); // measurement start
func(n); // execute the function being measured
end = clock(); // measurement end
printf("Execution time: %lf secondsn", (double)(end - start) / CLOCKS_PER_SEC);
}
5.2. Measuring Execution Time of Each Method
5.2.1. Trial Division (O(N))
Code
int is_prime(int n) {
if (n < 2) return 0;
for (int i = 2; i < n; i++) {
if (n % i == 0) return 0;
}
return 1;
}
void test_trial_division(int limit) {
int count = 0;
for (int i = 2; i <= limit; i++) {
if (is_prime(i)) count++;
}
printf("Total primes: %dn", count);
}
5.3. Comparison of Execution Times (Graphical)
Method
Complexity
For 10,000
For 100,000
For 1,000,000
Trial Division
O(N)
0.25 seconds
2.5 seconds
tens of seconds to several minutes
√N Trial Division
O(√N)
0.02 seconds
0.15 seconds
1.5 seconds
Sieve of Eratosthenes
O(N log log N)
0.001 seconds
0.005 seconds
0.03 seconds
The Sieve of Eratosthenes is overwhelmingly fast can be seen.
6. FAQ (Frequently Asked Questions)
In this section, we answer the most common questions about prime number testing in C.
Q1: Why use the square root for prime testing?
A: If a number N is not prime, there is always a divisor at or below the square root of N. For example, when N = 49, the divisor pairs are as follows.
1 × 49
7 × 7 (square root)
49 × 1
Divisors larger than the square root have already been checked in earlier steps, so you can reduce the computational complexity from O(N) to O(√N).
Q2: When should the Sieve of Eratosthenes be used?
A: The Sieve of Eratosthenes is ideal when you want to quickly find all primes within a given range. ✅ Cases where you should use the Sieve of Eratosthenes
Want to list primes from 1 to 1,000,000
Want to efficiently test the primality of multiple numbers
Q3: Does the C environment affect the speed of prime testing?
A: Yes, the speed of prime testing can vary significantly depending on the C compiler, optimization options, and runtime environment. ✅ Factors that affect performance
Type of compiler (GCC, Clang, MSVC, etc.)
Optimization options at compile time
CPU performance (especially affecting loop execution speed)
💡 Performance optimization tips
gcc -O3 prime.c -o prime
This allows the compiler to optimize loops, potentially making the processing faster.
7. Summary and Future Learning Directions
In the previous sections, we have thoroughly explained the basics to advanced topics of prime number testing using C.
7.1. Article Summary
🔹 What is a prime number?
A natural number that has no divisors other than 1 and itself
By checking up to the square root, you can reduce unnecessary calculations (time complexity O(√N))
🔹 Prime testing methods in C
Method
Complexity
Features
Trial division (basic)
O(N)
Suitable for beginners. Simple but slow
Trial division up to √N
O(√N)
Optimal for testing a single number for primality
Sieve of Eratosthenes
O(N log log N)
Ideal for generating a large number of primes
🔹 Choosing the optimal algorithm
Purpose
Recommended Algorithm
Determine if a single number is prime
Trial division up to √N
Create a list of primes within a range
Sieve of Eratosthenes
Testing large numbers greater than 10⁹
Miller–Rabin method (probabilistic)
7.2. Future Learning Directions
1️⃣ More advanced prime testing algorithms
Miller–Rabin prime test (probabilistic)
AKS prime test (deterministic)
2️⃣ Optimization techniques in C
Compiler optimization options (-O2, -O3)
Parallel processing using multithreading
3️⃣ Handling large numbers in C
Using the GMP (GNU Multiple Precision) library
7.3. Practical Project Ideas
✅ Project 1: Prime Counter ✅ Project 2: Prime Factorization Tool ✅ Project 3: Prime Search App
7.4. Summary
Trial division (basic) has a time complexity of O(N), making it slow and unsuitable for large numbers.
√N trial division runs in O(√N), suitable for single large-number checks.
Sieve of Eratosthenes runs in O(N log log N), allowing fast generation of prime lists.
Choosing the optimal algorithm based on the use case is important!