C Program to Check Prime Number with Output and Explanation
for (int i = 2; i * i <= n; i++) and check if (n % i == 0) to decide.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> #include <math.h> int main() { int n, i, isPrime = 1; printf("Enter a number: "); scanf("%d", &n); if (n < 2) { isPrime = 0; } else { for (i = 2; i * i <= n; i++) { if (n % i == 0) { isPrime = 0; break; } } } if (isPrime) printf("%d is a prime number.\n", n); else printf("%d is not a prime number.\n", n); return 0; }
Dry Run
Let's trace the input 7 through the code to see how it checks for prime.
Input number
User enters n = 7
Check if less than 2
7 is not less than 2, continue
Loop from 2 to sqrt(7)
sqrt(7) ≈ 2.64, so i goes from 2 to 2
Check divisibility
7 % 2 != 0, so no divisor found
No divisors found
isPrime remains 1, number is prime
Print result
Print '7 is a prime number.'
| i | n % i | isPrime |
|---|---|---|
| 2 | 1 | 1 |
Why This Works
Step 1: Start with input
We first get the number from the user to check if it is prime.
Step 2: Exclude numbers less than 2
Numbers less than 2 are not prime by definition, so we mark them immediately.
Step 3: Check divisors up to square root
We only check divisors up to the square root because any factor larger than that would have a matching smaller factor.
Step 4: Decide prime or not
If any divisor divides the number evenly, it is not prime; otherwise, it is prime.
Alternative Approaches
#include <stdio.h> int main() { int n, i, isPrime = 1; printf("Enter a number: "); scanf("%d", &n); if (n < 2) isPrime = 0; else { for (i = 2; i < n; i++) { if (n % i == 0) { isPrime = 0; break; } } } if (isPrime) printf("%d is a prime number.\n", n); else printf("%d is not a prime number.\n", n); return 0; }
#include <stdio.h> #include <math.h> int isPrime(int n) { if (n < 2) return 0; for (int i = 2; i * i <= n; i++) { if (n % i == 0) return 0; } return 1; } int main() { 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); return 0; }
Complexity: O(√n) time, O(1) space
Time Complexity
The loop runs up to the square root of n, so the time grows roughly with √n.
Space Complexity
Only a few variables are used, so space is constant O(1).
Which Approach is Fastest?
Checking up to the square root is faster than checking up to n-1, and using a function helps organize code but does not affect complexity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Check up to sqrt(n) | O(√n) | O(1) | Efficient primality test |
| Check up to n-1 | O(n) | O(1) | Simple but slower |
| Function-based check | O(√n) | O(1) | Reusable and clean code |