Popular Science article: Sieve method is a simple method of verifying prime numbers. It is said that the ancient Greek Eratosthenes (Eratosthenes, about 274-194 BC) invented, also known as Eratosthenes sieve method (Sieve of Eratosthenes).
To tell the truth, before I was in the case of the prime is to verify whether a number is a prime, with the definition of the easy to come to the conclusion, the code is as follows:
:Public static BOOLIsPrime (intN) by : {//Determine if n is a prime number : if(n < 2)return False; Note: for(inti = n-1; i > 1; i--) To : {//n divided by each of the natural numbers smaller than n 1 large : if(n% i = = 0): {//If it is divisible, it is not a prime number : return False; : } Ten: }//Otherwise it is prime number one:return True; : }
But in this way, if you require all prime numbers between two numbers x and y, you need to use a loop to determine:
1: for ( int i = x; i < y; i++) { 3: if (IsPrime (i)) { 5: console 6: }
7: }
Today's book of books by chance saw that the Sieve method may be more appropriate to deal with such problems--to find all prime numbers within a certain limit:
:private static List<int> Genprime (intj) by : {: List<int> Ints=NewList<int> (); Note: BitArraybts=NewBitArray(j+1); To : for(intx = 2; x < BTS. LENGTH/2; x + +): {: for(inty = x + 1; y < BTS. Length; y++): {: if(bts[y] = =false&& y% x = = 0) Ten: {One: bts[y] =true; : } : } : } : for(intx = 2; x < BTS. Length; x + +): {: if(bts[x] = =false): {: ints. ADD (x); : } : } : returnints; : }
However, if a range of prime numbers is required, a difference of two ranges is required:
1: List < int > Listresult = Genprime (x). Except (Genprime (y)). ToList ();
Then in another master's blog found a linear sieve algorithm, I changed it to C # code:
:private staticList<int> GenPrime1 (intx) by : {: intnum_prime = 0; Note: List<int> ints =NewList<int> (); To : BitArrayIsnotprime =NewBitArray(x); : for(inti = 2; i < x; i++) : {: if(!isnotprime[i]): {: ints. ADD (i); One : num_prime++; : } : for(intj = 0; J < num_prime && I * ints[j] < X; j + +) : {: isnotprime[i * ints[j]] =true; : if(!Convert. ToBoolean (i% ints[j])) : Break; : } : } : returnints; : }
Transfer to original post: General Sieve method for prime number + fast linear sieve method
PS. The first time to write a blog, if there is insufficient place please tell me, I must change!
C # Sieve method to find all prime numbers in the range