For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
Prime numbers play a crucial role in cryptography, number theory, and algorithm design. A C program to print 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, helping you sharpen your programming skills and deepen your understanding of C.
Boost your C programming skills with our Software Development courses — take the next step in your learning journey!
This is the simplest method for checking prime numbers in a C program to print prime numbers. It involves iterating through all numbers from 2 to num-1 and checking if any number divides num evenly. If you find such a number, num is not prime. Otherwise, it’s considered a prime number.
While this method is straightforward, it’s not the most efficient, especially for larger numbers.
Algorithm:
For an input num:
Code:
#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 2
if (num <= 1) {
printf("Not Prime\n");
return 0; // Exit the program if num is less than or equal to 1
}
// Iterative loop to check divisibility
for (i = 2; i < num; i++) {
if (num % i == 0) { // If divisible by i
count++; // Increment count
break; // Exit loop early if a divisor is found
}
}
// Check if count is greater than 0, then it's not prime
if (count > 0) {
printf("Not Prime\n");
} else {
printf("Prime\n");
}
return 0;
}
Output:
For input num = 7:
Enter a number: 7Prime
For input num = 8:
Enter a number: 8Not Prime
Explanation:
Time Complexity:
Space Complexity:
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.
In this method, we optimize the prime number program in C by breaking the loop early as soon as we find a divisor. This avoids unnecessary iterations after identifying that the number is not prime, improving efficiency.
Instead of checking all numbers up to n, we check only up to √n, since any factor larger than √n would already have a corresponding smaller factor.
This reduces the worst-case time complexity from O(n²) to O(n√n), making it much more efficient for large numbers by cutting down redundant checks.
Algorithm:
For an input num:
Code:
#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 the program if num is less than or equal to 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 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;
}
Output:
For input num = 7:
Enter a number: 7Prime
For input num = 8:
Enter a number: 8Not Prime
Explanation:
Time Complexity:
Space Complexity:
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.
In this method, we optimize the prime number program in C by reducing the number of iterations. Instead of checking divisibility up to num - 1, we only check divisibility up to num / 2.
This drastically cuts down the number of comparisons and helps speed up the process, though it is still not the most efficient method available.
For n = 1000, Method 1 does 999 checks, Method 3 reduces this to 500, but Method 2 exits early if a divisor is found, making it more efficient in practice.
Algorithm:
For an input num:
Code:
#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 if num is less than or equal to 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 the loop if a divisor is found
}
}
// If count is greater than 0, it's not prime
if (count > 0) {
printf("Not Prime\n");
} else {
printf("Prime\n");
}
return 0;
}
Output:
For input num = 7:
Enter a number: 7Prime
For input num = 8:
Enter a number: 8Not Prime
Explanation:
Time Complexity:
Space Complexity:
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.
This method significantly improves the efficiency of your prime number program in C by only checking for divisibility up to the square root of num. The reasoning behind this is simple: if num is divisible by some number i, then num / i is also a divisor.
The key idea is that factors always appear in pairs. If n is divisible by some i, then n / i is also a factor. If both factors were greater than √n, their product would exceed n, which is impossible.
For example, consider n = 36. Its factor pairs are (1,36), (2,18), (3,12), (4,9), and (6,6). Notice that all smaller factors appear before √36 = 6. Checking beyond √n is redundant because any divisor greater than √n would already have been paired with a smaller divisor that has been checked.
Algorithm:
For an input num:
Code:
#include <stdio.h>
#include <math.h> // For square root 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 if num is less than or equal to 1
}
// Loop from 2 to sqrt(num) to check divisibility
for (i = 2; i <= sqrt(num); i++) { // Use sqrt to limit the loop
if (num % i == 0) { // If divisible by i
count++; // Increment count
break; // Exit loop if a divisor is found
}
}
// If count is greater than 0, it's not prime
if (count > 0) {
printf("Not Prime\n");
} else {
printf("Prime\n");
}
return 0;
}
Output:
For input num = 7:
Enter a number: 7Prime
For input num = 8:
Enter a number: 8Not Prime
Explanation:
Time Complexity:
Space Complexity:
Next, let’s take another step toward optimization by skipping even iterations, further speeding up the process.
Skipping even numbers (except 2) reduces the number of checks by nearly half. Instead of iterating through all numbers up to √n, we only check odd numbers, since all even numbers (except 2) are composite.
In terms of complexity, the naive approach (Method 1) has O(n) time complexity. Method 4 (√n check) reduces it to O(√n). By skipping even numbers, we further cut down the number of iterations by a factor of 2, making it O(√n / 2).
For example, when n = 10,000, instead of checking up to 100 (as in Method 4), we check only 50 numbers, making the algorithm almost twice as fast for large inputs.
Algorithm:
For an input num:
Code:
#include <stdio.h>
#include <math.h> // For square root 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 for 2)
if (num <= 1) {
printf("Not Prime\n");
return 0; // Exit the program if num is less than or equal to 1
}
if (num == 2) {
printf("Prime\n");
return 0; // 2 is prime, exit the program
}
// Loop from 3 to sqrt(num), checking only odd numbers
for (i = 3; i <= sqrt(num); i += 2) { // Step 2 to skip even numbers
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;
}
Output:
For input num = 7:
Enter a number: 7Prime
For input num = 8:
Enter a number: 8Not Prime
Explanation:
Time Complexity:
Space Complexity:
Now, let’s dive into a different approach with recursion, where the program calls itself to check for primes.
In this method, we use recursion to check if a number is prime. The logic of checking divisibility is divided into smaller, self-contained checks. The program checks for divisibility from 2 to √num by calling the same function with updated parameters, making it a clean and elegant solution.
However, recursion comes with drawbacks, particularly in terms of space complexity. Each recursive call adds a new frame to the call stack, leading to O(√n) auxiliary space usage. For very large numbers, deep recursion can cause stack overflow, making iterative methods more memory-efficient.
Algorithm:
For an input num:
Code:
#include <stdio.h>
#include <math.h> // For square root function
// Recursive function to check for prime
int isPrime(int num, int i) {
if (i > sqrt(num)) { // Base case: if i exceeds sqrt(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;
}
Output:
For input num = 7:
Enter a number: 7Prime
For input num = 8:
Enter a number: 8Not Prime
Explanation:
Time Complexity:
Space Complexity:
Next, let’s explore a more advanced and efficient algorithm: the Sieve of Eratosthenes, to find prime numbers faster.
The Sieve of Eratosthenes algorithm is highly efficient for finding all prime numbers up to a given limit n. Instead of checking each number individually for primality, it iteratively marks the multiples of each prime starting from 2 as non-prime.
For n = 10^6, checking each number individually takes ~1000x more operations than the sieve, making it ideal for generating primes in bulk.
Algorithm:
For an input num (limit):
Code:
#include <stdio.h>
#include <stdbool.h>
void sieveOfEratosthenes(int num) {
// Create an array to mark primes
bool prime[num + 1];
// Initialize all entries as true. A value in prime[i] will
// be false if i is not a prime, true if i is a prime.
for (int i = 0; i <= num; i++) {
prime[i] = true;
}
// Start with the first prime number 2
prime[0] = prime[1] = false; // 0 and 1 are not primes
// Iterate over numbers and mark multiples as non-prime
for (int p = 2; p * p <= num; p++) {
if (prime[p] == true) { // If p is still prime
for (int i = p * p; i <= num; i += p) {
prime[i] = false; // Mark multiples of p as non-prime
}
}
}
// Print all 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;
}
Output:
For input num = 20:
Enter the limit up to which you want to print prime numbers: 20Prime numbers up to 20 are:2 3 5 7 11 13 17 19
Explanation:
Time Complexity:
Space Complexity:
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.
1. What is the main purpose of using a simple iterative solution in a prime number program in C?
A) To check divisibility by all numbers up to num-1
B) To use recursion for checking primes
C) To minimize the number of iterations
D) To store prime numbers in an array
2. Which of the following is an advantage of using the break condition in a prime number program in C?
A) It simplifies the algorithm
B) It reduces the number of unnecessary iterations
C) It improves the clarity of the program
D) It makes the code more flexible
3. What is the main optimization in the method that checks divisibility only up to num/2?
A) It eliminates the need for a loop
B) It checks divisibility for a smaller range
C) It skips even numbers
D) It uses recursion instead of loops
4. Why is checking divisibility up to √num more efficient than checking all the way to num-1?
A) Larger divisors are irrelevant
B) It checks fewer numbers
C) It reduces time complexity
D) It avoids checking odd numbers
5. What is the key benefit of skipping even iterations in a prime number program in C?
A) It ensures all divisibility conditions are checked
B) It speeds up the program by skipping unnecessary checks for even numbers
C) It avoids using a loop
D) It automatically optimizes the algorithm
6. Which of the following methods uses recursion to check if a number is prime?
A) Simple iterative solution
B) Sieve of Eratosthenes
C) Optimization by n/2 iterations
D) Basic recursion technique
7. How does the Sieve of Eratosthenes algorithm improve the efficiency of prime number checking?
A) By checking numbers in a random order
B) By iteratively marking non-prime numbers
C) By checking numbers up to num
D) By using recursion to identify prime numbers
8. What is the time complexity of the Sieve of Eratosthenes for finding prime numbers?
A) O(n)
B) O(n log log n)
C) O(√n)
D) O(n²)
9. Which method is most efficient for finding prime numbers in a large range?
A) Simple iterative solution
B) Optimization by break condition
C) Optimization by √n
D) Sieve of Eratosthenes
10. Why is space complexity O(n) in the Sieve of Eratosthenes method?
A) It stores numbers up to num in a boolean array
B) It uses recursion, which requires space
C) It stores only prime numbers in an array
D) It stores all factors of a number
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
C Program to check Armstrong Number
Factorial Program of a Number in C
Fibonacci Series Program in C Using Recursion
You can optimize your C program to print prime numbers by using methods like the Sieve of Eratosthenes or checking divisibility only up to √num to reduce the number of iterations.
The Sieve of Eratosthenes is the most efficient method for checking prime numbers in a large range, as it can quickly mark non-prime numbers up to a given limit.
Yes, you can use basic iterative methods for small numbers, but for larger numbers, methods like optimization by √n or the Sieve of Eratosthenes are better suited.
You can skip checking even numbers (other than 2) by starting the loop at 3 and incrementing by 2, which reduces unnecessary checks in your prime number program in C.
You can use recursion to check divisibility by calling the same function with updated parameters, reducing the logic to smaller checks for each divisor.
Yes, using the break condition in your prime number program in C helps stop further checks once a divisor is found, making it more efficient than checking all numbers up to num.
The Sieve of Eratosthenes marks all non-prime numbers efficiently, making it faster for generating primes up to a large number compared to checking each number individually.
You can adapt the Sieve of Eratosthenes by creating a boolean array for a specific range and marking the multiples of each prime within that range as non-prime.
For checking a small number of primes, the simple iterative solution or optimization by break condition works well, as they are easier to implement and run quickly.
The Sieve of Eratosthenes has a time complexity of O(n log log n), which is much faster for larger ranges than methods like simple iteration or checking divisibility up to num.
It’s difficult to find all primes up to a large number efficiently without using arrays, as storing the primality status of each number allows for faster identification of primes using methods like the Sieve of Eratosthenes.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.