C Program for Prime Numbers | Check & Print Primes
By Mukesh Kumar
Updated on Mar 21, 2025 | 20 min read | 1.5k views
Share:
For working professionals
For fresh graduates
More
By Mukesh Kumar
Updated on Mar 21, 2025 | 20 min read | 1.5k views
Share:
Table of Contents
Prime numbers play a crucial role in cryptography, number theory, and algorithm design. A C program for prime numbers helps identify numbers that are only divisible by 1 and themselves, making them fundamental in mathematics and computing.
Writing a prime number program in C enhances your understanding of loops, conditions, and efficient algorithms for number processing.
In this tutorial, you'll learn how to create this program step-by-step using 7 methods, helping you sharpen your programming skills and deepen your understanding of C.
The C program for prime numbers can be implemented using a basic iterative approach, where we check for divisibility from 2 to num - 1. If num is divisible by any of these numbers, it is not prime; otherwise, it is prime.
This method is easy to understand but highly inefficient for large numbers. Since it performs (n - 2) iterations, its time complexity is O(n), making it unsuitable for larger inputs. More optimized approaches should be used for better performance.
The C program for prime numbers in this method follows a brute-force approach, checking divisibility for all numbers from 2 to num - 1.
This method works for small numbers but becomes impractical for large numbers due to its high computational cost.
#include <stdio.h>
int main() {
int num, i, count = 0;
// Input number to check
printf("Enter a number: ");
scanf("%d", &num);
// Check if num is less than 2
if (num <= 1) {
printf("Not Prime\n");
return 0;
}
// Iterative loop to check divisibility
for (i = 2; i < num; i++) {
if (num % i == 0) { // If divisible by i
count++;
break; // Exit loop early if a divisor is found
}
}
// Prime check based on count value
if (count > 0) {
printf("Not Prime\n");
} else {
printf("Prime\n");
}
return 0;
}
For input num = 7:
Enter a number: 7
Prime
For input num = 8:
Enter a number: 8
Not Prime
Limitations:
While this method works for small ranges, it becomes inefficient for larger numbers. The time complexity is O(n²) in the worst case, as each number is checked against all previous numbers.
This results in significant performance issues when dealing with large ranges, making it unsuitable for scalable applications like cryptography or big-data processing.
Also Read: Algorithm Complexity and Data Structure: Types of Time Complexity
Now that we’ve covered the basics, let’s speed things up by optimizing break conditions to exit early.
The C program for prime numbers can be optimized using a break condition to exit the loop as soon as a divisor is found. This prevents unnecessary iterations, making the program much faster. Instead of checking all numbers up to n, we only check up to √n, because any factor larger than √n would already have a corresponding smaller factor.
By applying this method, we improve the worst-case time complexity from O(n²) to O(n√n), significantly reducing redundant checks. This makes it more efficient for larger numbers, especially when combined with other optimizations.
This C program for prime numbers optimizes the divisibility check by exiting early as soon as a divisor is found. The key advantages are:
Iteration |
Divisibility Check |
Found a Divisor? |
Loop Continues? |
i = 2 | 50 % 2 == 0 ✅ | Yes | Stop (Exit Early) |
For non-prime numbers, this method exits much earlier, drastically improving efficiency.
#include <stdio.h>
int main() {
// Declare the variables
int num, i, count = 0;
// Input number to check
printf("Enter a number: ");
scanf("%d", &num);
// Check if num is less than or equal to 1
if (num <= 1) {
printf("Not Prime\n");
return 0; // Exit if num is 0 or 1
}
// Loop from 2 to num/2 to check divisibility
for (i = 2; i <= num / 2; i++) {
if (num % i == 0) { // If divisible by i
count++; // Increment count
break; // Exit loop early
}
}
// Determine if num is prime
if (count > 0) {
printf("Not Prime\n");
} else {
printf("Prime\n");
}
return 0;
}
For input num = 7:
Enter a number: 7
Prime
For input num = 8:
Enter a number: 8
Not Prime
Space Complexity Analysis
Also Read: Top Time Complexities that every Programmer Should Learn
Next, let’s take it a step further and reduce the number of iterations by half to boost efficiency even further.
The C program for prime numbers can be optimized by reducing the number of iterations to n/2. Instead of checking divisibility up to num - 1, we only check up to num / 2, significantly cutting down comparisons. While this method is faster than naive approaches, it is still not the most efficient. More advanced methods, like √n optimization, provide better performance.
For example, for n = 1000:
This C program for prime numbers improves efficiency by checking divisibility only up to num / 2. The logic is simple:
#include <stdio.h>
int main() {
// Declare variables
int num, i, count = 0;
// Input number to check
printf("Enter a number: ");
scanf("%d", &num);
// Check if num is less than or equal to 1
if (num <= 1) {
printf("Not Prime\n");
return 0; // Exit the program early
}
// Loop from 2 to num/2 to check divisibility
for (i = 2; i <= num / 2; i++) {
if (num % i == 0) { // If divisible by i
count++; // Increment count
break; // Exit the loop early
}
}
// If count is greater than 0, it's not prime
if (count > 0) {
printf("Not Prime\n");
} else {
printf("Prime\n");
}
return 0;
}
For input num = 7:
Enter a number: 7
Prime
For input num = 8:
Enter a number: 8
Not Prime
Also Read: Top 25+ C Programming Projects for Beginners and Professionals
Next, let’s take it up a notch by limiting our checks to the square root of num for even greater efficiency.
The C program for prime numbers can be optimized using the square root (√n) method, significantly reducing the number of divisibility checks. The key idea is that factors always appear in pairs—if a number n is divisible by i, then n / i is also a factor. This means we only need to check up to √n, as any divisor greater than √n would have already been paired with a smaller factor. This approach improves efficiency compared to naive methods.
The C program for prime numbers using the √n method drastically reduces unnecessary computations. Instead of checking all numbers up to n - 1, we only check up to √n, because:
For n = 36, its factor pairs are:
(1,36), (2,18), (3,12), (4,9), (6,6)
Since all factors ≤ √36 (i.e., 6) appear before larger factors, checking beyond √n is unnecessary.
#include <stdio.h>
#include <math.h> // For sqrt() function
int main() {
// Declare variables
int num, i, count = 0;
// Input number to check
printf("Enter a number: ");
scanf("%d", &num);
// Check if num is less than or equal to 1
if (num <= 1) {
printf("Not Prime\n");
return 0; // Exit the program early
}
// Loop from 2 to sqrt(num) to check divisibility
for (i = 2; i <= sqrt(num); i++) {
if (num % i == 0) { // If divisible by i
count++;
break; // Exit the loop early
}
}
// Prime check
if (count > 0) {
printf("Not Prime\n");
} else {
printf("Prime\n");
}
return 0;
}
For input num = 7:
Enter a number: 7
Prime
For input num = 8:
Enter a number: 8
Not Prime
The C program for prime numbers can be optimized by skipping even iterations, except for 2. Since even numbers (except 2) are composite, checking only odd numbers up to √num significantly reduces computations. This method is faster than the standard O(√num) approach, making it more efficient for large numbers.
The C program for prime numbers in this method eliminates even-numbered checks, improving performance. Instead of checking every number up to √num, the program only evaluates odd numbers (3, 5, 7, 9...). This technique effectively halves the number of iterations, speeding up prime number detection.
For n = 10,000, instead of checking 100 numbers (as in a standard O(√num) method), this approach checks only 50, effectively doubling the execution speed.
#include <stdio.h>
#include <math.h> // For sqrt() function
int main() {
// Declare variables
int num, i, count = 0;
// Input number to check
printf("Enter a number: ");
scanf("%d", &num);
// Check if num is less than or equal to 1 or even (except 2)
if (num <= 1) {
printf("Not Prime\n");
return 0; // Exit early
}
if (num == 2) {
printf("Prime\n");
return 0; // 2 is prime, exit early
}
// Loop from 3 to sqrt(num), skipping even numbers
for (i = 3; i <= sqrt(num); i += 2) {
if (num % i == 0) { // If divisible by i
count++;
break; // Exit the loop early
}
}
// Prime check
if (count > 0) {
printf("Not Prime\n");
} else {
printf("Prime\n");
}
return 0;
}
For input num = 7:
Enter a number: 7
Prime
For input num = 8:
Enter a number: 8
Not Prime
Now, let’s dive into a different approach with recursion, where the program calls itself to check for primes.
Boost your C programming skills with our Software Development courses — take the next step in your learning journey!
Recursion provides an elegant way to check for prime numbers by breaking the problem into smaller subproblems. The function calls itself recursively, checking divisibility from 2 to √num. However, recursion increases space complexity, making it less efficient for large inputs.
This method utilizes a recursive approach to check whether a number is prime. Instead of iterating through divisors, the function calls itself with an updated divisor (i) until it reaches √num.
The key advantage is code simplicity, but it has a drawback—each recursive call adds stack space, leading to O(√num) auxiliary space usage. If the input number is large, recursion may cause stack overflow, making iterative methods more efficient.
#include <stdio.h>
#include <math.h> // For sqrt() function
// Recursive function to check for prime
int isPrime(int num, int i) {
if (i > sqrt(num)) { // Base case: If i exceeds √num, num is prime
return 1; // Return true (1) as num is prime
}
if (num % i == 0) { // If num is divisible by i, it's not prime
return 0; // Return false (0) as num is not prime
}
return isPrime(num, i + 1); // Recursively check the next divisor
}
int main() {
int num;
// Input number to check
printf("Enter a number: ");
scanf("%d", &num);
// Check if num is less than or equal to 1
if (num <= 1) {
printf("Not Prime\n");
return 0; // Exit if num is less than or equal to 1
}
// Call recursive function to check for prime
if (isPrime(num, 2)) { // Start recursion with i = 2
printf("Prime\n");
} else {
printf("Not Prime\n");
}
return 0;
}
For input num = 7:
Enter a number: 7
Prime
For input num = 8:
Enter a number: 8
Not Prime
The Sieve of Eratosthenes is one of the most efficient algorithms for finding all prime numbers up to a given limit n. Instead of checking each number individually, it iteratively marks the multiples of each prime starting from 2 as non-prime.
This optimization makes it significantly faster than previous methods. For n = 10⁶, the sieve is ~1000 times more efficient than checking each number separately, making it the best approach for generating primes in bulk.
The Sieve of Eratosthenes works by using a boolean array to keep track of prime numbers and marking multiples as non-prime.
#include <stdio.h>
#include <stdbool.h>
// Function to implement Sieve of Eratosthenes
void sieveOfEratosthenes(int num) {
// Boolean array to mark prime numbers
bool prime[num + 1];
// Initialize all numbers as prime
for (int i = 0; i <= num; i++) {
prime[i] = true;
}
// 0 and 1 are not prime numbers
prime[0] = prime[1] = false;
// Start marking multiples as non-prime
for (int p = 2; p * p <= num; p++) {
if (prime[p]) { // If still marked as prime
for (int i = p * p; i <= num; i += p) {
prime[i] = false; // Mark multiples as non-prime
}
}
}
// Print prime numbers
printf("Prime numbers up to %d are:\n", num);
for (int p = 2; p <= num; p++) {
if (prime[p]) {
printf("%d ", p);
}
}
printf("\n");
}
int main() {
int num;
// Input number to define the limit
printf("Enter the limit up to which you want to print prime numbers: ");
scanf("%d", &num);
// Call the sieve function
sieveOfEratosthenes(num);
return 0;
}
Enter the limit up to which you want to print prime numbers: 20
Prime numbers up to 20 are:
2 3 5 7 11 13 17 19
Time Complexity: O(n log log n)
Method |
Complexity |
Number of Checks for n = 10⁶ |
Naive Iteration | O(n) | ~1,000,000 checks |
Divisibility up to √n | O(√n) | ~1,000 checks |
Sieve of Eratosthenes | O(n log log n) | Most efficient |
Space Complexity: O(n)
Also Read: What Are Storage Classes in C?
To help reinforce your learning, test your knowledge with a quiz on prime number concepts and C programming techniques covered in this tutorial.
Test your understanding of prime number concepts and C programming techniques covered throughout this tutorial! From basic logic to advanced optimizations, let's see how well you know the methods for finding prime numbers in C.
🔹 Question: Write a C program to check whether a given number is prime. The program should take an integer as input and output whether it is prime or not. Optimize the solution for efficiency.
Here’s an efficient C program to check for prime numbers using the square root method to reduce unnecessary iterations:
#include <stdio.h>
#include <math.h>
// Function to check if a number is prime
int isPrime(int num) {
if (num < 2) return 0; // 0 and 1 are not prime numbers
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0)
return 0; // Not a prime number
}
return 1; // Prime number
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (isPrime(num))
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
return 0;
}
✔️ The program defines a function isPrime() that checks divisibility up to √num, improving efficiency.
✔️ The main() function takes user input and calls isPrime() to determine if the number is prime.
✔️ The output clearly states whether the entered number is prime or not.
💡 Practice Tip: Try modifying the code to check prime numbers within a given range!
As you deepen your understanding of prime number concepts and C programming techniques, it's important to continue upskilling to stay ahead in programming. Let’s see how upGrad can help you build a stronger foundation in C programming and tackle more advanced topics like algorithm optimization and data structures.
upGrad’s courses provide expert training in C programming, covering essential concepts like loops, recursion, and algorithm optimization. You’ll gain hands-on experience, solve real-world challenges, and sharpen your programming skills.
Below are some relevant upGrad courses to elevate your programming skills and advance your career:
You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!
Similar Reads:
Explore C Tutorials: From Beginner Concepts to Advanced Techniques
Addition of Two Numbers in C: A Comprehensive Guide to C Programming
String Anagram Program in C
C Program to check Armstrong Number
Factorial Program of a Number in C
Fibonacci Series Program in C Using Recursion
In this blog, we explored various methods to implement a C program for prime numbers, including basic divisibility checks, the Sieve of Eratosthenes, recursive functions, and trial division methods. Each approach offers different levels of efficiency, making it crucial to choose the right method based on your requirements.
Whether you're checking a single number or generating a list of prime numbers, understanding these techniques will enhance your C programming skills. Keep practicing and experimenting to optimize your C program for prime numbers for better performance and accuracy!
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources