#include<stdio.h>
#include<conio.h>
void main()
{ int x,z,y=2;
//x is lower limit and z is upper limit of range
printf(“enter the no.”);
scanf("%d%d",&x&z);
while(x<=z)
{
while(y<=x)
{
if(x%y==0)
{
break;
}
y++;
if(x==y)
printf(“prime no.=%d \n”,x);
}
x++;
}
getch();
}
what would be the output??
Que: What would be the output??
Ans: compilation error.
Change your scanf statement to
scanf("%d %d",&x,&z);
^
Also for finding a prime number, your implementation is wrong.
try this way
if(x<=2 && z>=2)
printf("prime no.=2 \n");
while(x<=z)
{
y=2;
while(y<=x)
{
if(x%y==0)
{
break;
}
y++;
if(x==y)
printf("prime no.=%d \n",x);
}
x++;
}
Read more about sieves, @vinayawsm’s algorithm is probably ok (didn’t test it), but with that slow implementation complexity is O(N2), what is something you cannot use for z=100.000, with sieves you can get the results for z=10.000.000
For example I wrote something about sieves here.
As a related problems you can try KPRIME.
1 Like
@betlista yup true. I have given a slow propagation code. It was just the edited version of his actual code so that he could understand better.
The idea used for generating prime numbers in a range is known as a segmented sieve. I would suggest you first look at the normal sieve of Eratosthenes . In normal sieve you eliminate all factors of the number starting from 1. .For this problem ,we need to cancel out the factors of numbers starting from the closest possible number to the starting of the segment interval to make it run in time.
Please look at the submissions for this problem for code.
just so you know, “using while loop” means nothing at all, since a for loop can be rewritten as a while loop