How to check a number is prime or not in C

Posted on 03rd July 2013

This is a C program to check if a number if prime or not

A prime number is a number which is not completely divisible by any number except 1 and itself.

If n is the number to be checked, the program will check if n is completely divisble by any number from 2 to n divided by 2

Strictly speaking the check need to be done only till the square root of n but to keep the program simple we will carry on the division until n/2


 /* **********************************************
 * Program to check a number is Prime or not	*

#include <stdio.h>
#include <conio.h>

int main() 
 int num, i;

 // Read a number
 printf("Enter a number : ");

//Check if the number is divsible
for (i=2; i <= num / 2; i++) {
	if (num % i == 0) {
		printf("%d is not a prime number. It is completely divisible by %d",num,i);
		return 0;

printf("%d is a prime number",num);

 // Wait for key press

return 0;

Program Output

Enter a number : 1324801
1324801 is not a prime number. It is completely divisible by 1151

Post a comment


aer | August 26, 2018 11:21 AM |

division by 2 looks like a good idea, but offers 4 as prime

Adam | September 4, 2018 11:39 AM |

Thanks for pointing it out..the program is now corrected. it should be i <= num/2