Prime Number

//To check whether the given number is prime or not
#include<stdio.h>
void main()
{
int i, n;
printf(“enter the value of n\t”);
scanf(“%d”,&n);
for(i=2;i<=n;i++)
{
if(n%i==0)

break;

}
if(i==n)
printf(“\n%d is prime number”,n);
else
printf(“\n%d is not prime”,n);
}

OUTPUT

Logic Description:

Since every number is divisible by 1.So i started to check the remainder value from 2. If the number is completely divisible by any number between 1 and and n except 1 and and n then the number is not prime else our count(i) will increase up-to n.When i and n are equal, the given number is never divided between 1 and the number because if the number is divided at once immediately our program break from the main logic and i and n never be equal. In this way prime and non-prime is checked.

Prime Number Between Range(1-1000)

#include<stdio.h>
void main()
{
int i, j;
for(j=1;j<=1000;j++)

{

for(i=2;i<=j;i++)
{
if(j%i==0)

break;

}
if(j==i)
printf(“\t%d”,j);

}
}

OUTPUT

Here the range is fixed from 1 -1000. We can change the range according to our requirement.The range can also be defined at run time by taking input from keyboard.

Leave a Reply

Your email address will not be published.