Блог пользователя ap_hawkdown

Автор ap_hawkdown, 12 лет назад, По-английски

Sieve of Eratosthenes used to determine prime numbers. A bool array in taken and initialized to false
first of all it starts with 2 and updates index of bool array of all multiples of 2 to be true..

like 4,6,8..but not 2 which is kept false. next false number is picked which is 3..and all its multiples are updated true like 6,9,12,15...updated true but 3 is kept false

similarly it is followed..

all numbers in the end which are false are primes.

then next false number is picked

int main() { static bool b[100000];

for(int i=2;i<=30000;i+=1)

{

if(!b[i])

{for(int j=2;j*i<30000;j++)

{

    b[i*j]=true;

}

}

} for(int i=2;i<30000;i++)

{

if(!b[i])

{

printf("%d",i);

}

}

return 0;

}

  • Проголосовать: нравится
  • -11
  • Проголосовать: не нравится

»
12 лет назад, скрыть # |
 
Проголосовать: нравится -7 Проголосовать: не нравится

We can reduce the number of iterations.

We only need to iterate i from 2 to sqrt(N), where N is the upper bound.

And j can start from i.

Check this code.

This is because any composite number has a divisor that does not exceed its square root.

(proof: Let n be a composite. There exists a, b (1 < a <= b < n) s.t. a*b=n. Then a must be less than or equal to sqrt(n))

»
12 лет назад, скрыть # |
Rev. 2  
Проголосовать: нравится +8 Проголосовать: не нравится

If you just want to generate prime number in [1,n], you can try this simple algorithm. It's running time is O(n).

»
12 лет назад, скрыть # |
Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

your suggestions are welcomed. Guys i am just beginner programmer.This is my very first post.It may not be best solution but i posted it for beginner programmers(easy to understand) and my future reference.

Thanks for your suggestions in the matter.