C Program to check the given number is prime or not
Objective
Write a C program to check whether a given number is Prime or not.
Algorithm / Approach
- Read a number
nfrom the user. - Initialize a flag variable
flag = 1(assuming the number is prime). - Loop from
i = 2up to the square root ofn(sqrt(n)). - Inside the loop, check if
nis perfectly divisible byi(n % i == 0). - If it is divisible, set
flag = 0and usebreakto exit the loop early. - After the loop, if
flag == 1, print Prime; else print Not Prime.
main.c
#include<stdio.h>
#include<math.h>
int main( ) {
int i, n, flag=1;
printf("Enter Value of N: ");
scanf("%d", &n);
for(i=2; i<=sqrt(n); i++) {
if(n%i == 0) {
flag = 0;
break;
}
}
if(flag == 1) {
printf("%d is PRIME NO.\n",n);
}
else {
printf("%d is NOT PRIME NO.\n",n);
}
return 0;
}
Expected Output
Enter Value of N: 17 17 is PRIME NO. Enter Value of N: 9 9 is NOT PRIME NO.
Explanation of the Program
- A Prime number is a number greater than 1 that is only divisible by 1 and itself (e.g., 2, 3, 5, 7, 11).
- The most efficient way to check for primality is to loop up to the square root of the number. If a number is divisible by a larger number, that larger number would correspond to a smaller factor that we already checked!
- The
breakstatement is an optimization. As soon as we find a single divisor, we know the number is NOT prime. There is no need to keep checking the rest of the numbers, so we break out of the loop immediately.
Complexity
Time Complexity
O(√n) - Loop runs up to the square root of n.
Space Complexity
O(1)