Saturday 2 September 2017

Program to Check Whether a Number is Prime or Not

#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:

Post a Comment