C Programming

How to find prime numbers in a given range

Logic behind the program is to check till half of the number (n/2) because it has been observed that the remainders get repeated after half of the number. Therefore, checking for remainders till n/2 is sufficient enough. The use of modulus operator(%) is important in this regard.

Related : Checking Prime Number in VB.Net

Language : C

[sourcecode language='c']
//To find prime numbers in a given range

#include
#include

void main()
{
int n1, n2,i,j, flag;

printf(“Enter the lower limt : “);
scanf(“%d”, &n1);

printf(“Enter the upper limt : “);
scanf(“%d”, &n2);
clrscr();
printf(“The following are the prime numbers in the following range %d to %d”,n1,n2);
for(i=n1;i<=n2;i++)
{ flag =0;

for(j=2;j<=i/2;j++)
{
if(i%j==0)
{
flag=1;
break;
}
}
if (flag==0)
printf(“\t%d “, i);
}

getch();
}
[/sourcecode]



Leave a Comment

Notify me of followup comments via e-mail. You can also subscribe without commenting.


WordPress - Vaibhav Kanwal