Sunday, October 13, 2013

finding all prime numbers in [1;N] for O(nlogn).the sieve of Eratostenes

Suppose we need to find all prime numbers between 1 and N. Usually we check if the number is prime by looking at the numbers from 1 to sqrt(K) (K is the number we want to check for). If we want to find all the prime numbers between 1 and N using this method we will have a time limit problem. It will take N*sqrt(N). There is a better way of finding the number in NlogN time. For this we will need a boolean array A[N]. A[i] will be false if the number i is prime otherwise it will be true.
 Here is the pseudocode of the sieve of Eratosfen.
    for(i=2;i<=N;i++)
    {
         if( a[i] is false)
         {
               mark all the divisors of i as true.
         }
    }
lets look at that on a small example
1 2 3 4 5 6 7 8 9 10
f  f  f  f  f  f  f  f  f   f
 number 1 is not prime but we will keep that as false.
Now our loop will continue until it meets a false value. It is the number 2.
2 is prime so our condition is met. Now we know that every number which is divisible on 2 is not a prime number . We go through the number form 2 to 10 and check if the current number is divisible on 2 we mark it as true ( not prime).
1 2 3 4 5 6 7 8 9 10
f  f  f  t  f  t  f  t  f   t
Next step is checking 3. 3 is false which means that 3 is prime so we do the same action again.
We loop through all the numbers and mark the numbers which are divisible on 3 (except 3 himself)
1 2 3 4 5 6 7 8 9 10
f  f  f  t  f  t  f  t  t   t
Now we are checking 4. 4 is true which means that we know that 4 is not prime.
We move to next step.
5 is false so we have to mark all the number which are divisible on 5
1 2 3 4 5 6 7 8 9 10
f  f  f  t  f  t  f  t  t   t
So, we got that 2,3,5,7 are primes in 5*log10


IF YOU HAVE ANY QUESTIONS LEAVE THEM IN COMMENTS NO QUESTION WILL BE UNANSWERED.

3 comments:

  1. How it is log 10? Can you please explain?

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. As the reciprocal sum of primes diverges as log(logn) and hence tight asymptotic complexity is O(nlog(logn)).
    The loose upper bund is O(nlogn) and tight upperbound is O(nlog(logn)).

    ReplyDelete