So today i learnt Sieve of Eratosthenes
the sources that i uses was anuj bhaiyas dsa course its really a interesting one
and i used geeks for geeks thats also pretty cool trick to figure out the prime number
finding a prime number is relly a tough when the number gets bigger and bigger
SO WHATS DIFFERENT IN IT ??
in it we first take a array of length n (basically its a bollean array so it contains yes or no) intially we make it yes
then we run a loop from 2-√n (if we focus here the loop intially is reduced so we save a lots of time ofcourse thats also true if you use ssd)
so now when we run loop for 1st the value of i(loop varible) which is 2 so we make all the multiples of 2 as false for example in the array the 4th,6th,8th10th...... positions are marked false
now when the i is 3 we make all the multiples of 3 marked as false
for example 6th,9th,12....
thing to note is that we mark all the multiple excepet itself that is (2nd in case of i=2 and 3rd in case of i=3)
and we keep on doning till i=√n
and finally what we achive is a prime nuber
for eg
exception initially we mark the first position as false
in this eg we have taken n=12
1st position=false ;2nd position=true ;3rd position=true ; 4th position=true ; 5th position=true ; 6th position=true ; 7th position=true ;8th position=true ;9th position=true ;10th position=true ;11th position=true ;12th position=true
after i=2(or running the loop 1st time)
1st position=false ;2nd position=true ;3rd position=true ; 4th position=false ; 5th position=true ; 6th position=false; 7th position=true ;8th position=false ;9th position=true ;10th position=false ;11th position=true ;12th position=false
after i=2(or running the loop 1st time)
1st position=false ;2nd position=true ;3rd position=true ; 4th position=false ; 5th position=true ; 6th position=false; 7th position=true ;8th position=false ;9th position=false;10th position=false ;11th position=true ;12th position=false
what we get is
2nd position=true ;3rd position=true ; 5th position=true ; 7th position=true;11th position=true
here we run loop only 2 times cause √12=3(approx)
so thats the advantage
we can find the prime number in a range using this trick
it can also be applied to find the prime number individually as what we learn in our primary classes of coding
which is the answer
thanks for reading
PPG
Comments
Post a Comment