Prime Number Program in C with Output
Check whether an integer is prime in C, and print all prime numbers from 1 to n.
- Time
O(sqrt(n)) to check one number, about O(n sqrt(n)) to print primes up to n - Space
O(1) - Hints3
- Read4 min
A prime number is greater than 1 and divisible only by 1 and itself. In C, write int isPrime(int n): return 0 if n < 2, then loop i from 2 while i <= n / i, and return 0 if n % i == 0. If the loop ends, return 1. To print primes from 1 to n, call isPrime(i) for every i from 1 to n and print the ones that return 1.
Problem statement
Write a prime number program in C.
- Read a number and print whether it is prime.
- Print all prime numbers from 1 to that number.
For example, 29 is prime, and the primes from 1 to 30 are
2 3 5 7 11 13 17 19 23 29.
A single positive integer n.
Whether n is prime, followed by all primes from 1 to n.
Examples
n = 2929 is a prime numberNo number from 2 to 5 divides 29, and 6 x 6 = 36 is already more than 29.
n = 3030 is not a prime number30 % 2 == 0, so 30 has a divisor other than 1 and itself.
primes from 1 to 302 3 5 7 11 13 17 19 23 29These ten numbers have exactly two divisors each.
Constraints
- n fits in a 32-bit int
- Numbers less than 2 are not prime
Think before you code
Reveal the questions to ask yourself first
- Why is 1 not prime?
- If 91 = 7 x 13, do you need to test 13 after finding 7?
- What should a C function return to mean "true" or "false"?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
Prime logic in C
A prime has exactly two divisors. So try every divisor from 2 upwards. If one divides
n with remainder 0, n is not prime.
You only need to go up to the square root of n. Divisors come in pairs (for 36:
2 x 18, 3 x 12, 4 x 9, 6 x 6), and in each pair one number is at most sqrt(n).
Check prime number in C
- If
n < 2, return 0. - For
i = 2whilei <= n / i: ifn % i == 0, return 0. - Return 1.
i * i <= n is the usual way to write the condition. For n close to the int
limit, i * i can go past 2147483647 (46341 x 46341 = 2147488281). i <= n / i
means the same thing and never overflows.
Prime numbers 1 to n in C
Loop i from 1 to n and print i whenever isPrime(i) returns 1.
| Method | Divisors tried for n = 97 |
|---|---|
| 2 to n - 1 | 95 |
| 2 to n / 2 | 47 |
| 2 to sqrt(n) | 8 |
Dry run
Walk through the example step by step
isPrime(29):
i | 29 / i | i <= 29 / i | 29 % i
--+--------+-------------+-------
2 | 14 | yes | 1
3 | 9 | yes | 2
4 | 7 | yes | 1
5 | 5 | yes | 4
6 | 4 | no, stop | -
No divisor was found, so the function returns 1 and 29 is prime.
Solution
Reveal the full C solution
#include <stdio.h>
int isPrime(int n) {
if (n < 2) {
return 0;
}
for (int i = 2; i <= n / i; i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main(void) {
int n;
printf("Enter a number: ");
scanf("%d", &n);
if (isPrime(n)) {
printf("%d is a prime number\n", n);
} else {
printf("%d is not a prime number\n", n);
}
printf("Prime numbers from 1 to %d: ", n);
for (int i = 1; i <= n; i++) {
if (isPrime(i)) {
printf("%d ", i);
}
}
printf("\n");
return 0;
}Output (two separate runs):
Enter a number: 29
29 is a prime number
Prime numbers from 1 to 29: 2 3 5 7 11 13 17 19 23 29
Enter a number: 30
30 is not a prime number
Prime numbers from 1 to 30: 2 3 5 7 11 13 17 19 23 29
C has no bool type unless you include <stdbool.h>, so the function returns 1 for
true and 0 for false. if (isPrime(n)) treats any non-zero value as true.
The flag version from lab records
Many C lab manuals use a flag variable and test divisors up to n / 2:
#include <stdio.h>
int main(void) {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n <= 1) {
flag = 1;
}
for (i = 2; i <= n / 2; i++) {
if (n % i == 0) {
flag = 1;
break;
}
}
if (flag == 0) {
printf("%d is a prime number.\n", n);
} else {
printf("%d is not a prime number.\n", n);
}
return 0;
}
Enter a positive integer: 17
17 is a prime number.
Enter a positive integer: 1
1 is not a prime number.
It is correct, but it tries about n / 2 divisors instead of sqrt(n). For a large
prime like 1000003 that is 500000 checks instead of about 1000.
Prime numbers 1 to n with a nested loop and count
Without a separate function, put the check inside the outer loop:
#include <stdio.h>
int main(void) {
int n, count = 0;
printf("Enter n: ");
scanf("%d", &n);
for (int num = 2; num <= n; num++) {
int isPrime = 1;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
isPrime = 0;
break;
}
}
if (isPrime) {
printf("%d ", num);
count++;
}
}
printf("\nTotal primes: %d\n", count);
return 0;
}
Enter n: 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Total primes: 25
isPrime is reset to 1 for every new num. Forgetting that reset is a common bug.
The Python version is the prime number program in Python. The Java versions are check whether a number is prime and print all prime numbers between 1 and n. More practice is in loop programs in C.
O(sqrt(n)) to check one number, about O(n sqrt(n)) to print primes up to nO(1)Review before the interview
Common mistakes
- Treating 1 as prime. Return 0 for any n < 2.
- Not resetting the flag (isPrime = 1) inside the outer loop when printing a range, so every number after the first composite is skipped.
- Writing i < sqrt(n) instead of i <= sqrt(n). Then 25 and 49 are reported as prime.
- Printing "prime" inside the inner loop the first time a divisor fails. You can only decide after all divisors have been tried.
Edge cases to test
- 2 is the smallest prime and the only even one. The loop does not run for it, so it returns 1.
- 0, 1 and negative numbers return 0.
- Perfect squares like 49 are caught when i reaches 7, since 7 <= 49 / 7.
- n near 2147483647: use i <= n / i, not i * i <= n, to avoid overflow.
Interview follow-ups
- How would you print the first n prime numbers instead of primes up to n?
- How does the Sieve of Eratosthenes print primes up to n faster?
- How would you skip even divisors after checking 2?
Keep practising
Check Whether a Number Is Prime
Hints · Dry run · SolutionSolve Similar problemPrint All Prime Numbers Between 1 and N
Hints · Dry run · SolutionSolve Similar problemPrime Number Program in Python with Output
Hints · Dry run · SolutionSolve Similar problemGenerate the First N Prime Numbers
Hints · Dry run · SolutionSolve Related learningLearn C Programming Step By Step
TutorialLearn Related learningFunctions For Beginners
TutorialLearn Related learningC Programming Interview Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartBuilding your programming basics?
CodeBegun’s programs build problem-solving with mentor review and mock interviews, online or in Madhapur, Hyderabad.
