Search This Blog

Program to Check Whether a Number is Prime or Not

This is a c program to check whether a given number is prime or not. To check whether a number 'n' is prime or not, it is enough to check whether it is divisible by any number less than or equal to square root of n. If there is any number i less than or equal to square root of n which divides n completely, then it is not prime. Otherwise it is prime.


#include<stdio.h>
#include<math.h>

int isPrime(int n)
{
int root,i;
//Calculating square root of n
root=sqrt(n);
/*
check n against all numbers from 2 to square root of n,
whether n is divisible by the number
*/
for(i=2;i<=root;i++)
    {
    //if divisible, not prime (return zero)
    if(n%i==0)
        return 0;
    }
return 1;
}

void main()
{
int input;
printf("\nEnter the number\n");
scanf("%d",&input);
if(isPrime(input))
    printf("\nIt is prime\n");
else
    printf("\nIt is not prime\n");
}

No comments: