Can anyone tell me how to implement Sieve of Eratosthenes algorithm in C? I need to generate prime numbers but my algorithm is slow.
My code:
#include <stdio.h>
int prime(long int i)
{
long int j;
int state = 1;
for(j=2;j<i;j++)
{
if((i%j)==0){state=0;break;}
}
return state;
}
int main()
{
int t;
long int m,n,i;
scanf("%d", &t);
while(t--) {
scanf("%d %d", &m,&n);
for(i=m;i<=n;i++)
{
if(i==1){
//do nothing for 1
} else{
if(prime(i))printf("%d
",i);
}
}
}
return 0;
}
t
is the number of test cases m and n is the range between which prime are to be printed.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…