Rehabilitation program of linear sieve

 

If I give you a n, let you all primes less than n output, how would you do?

The best approach is to think of a enum, and then test complexity O (n * √n)

 

That there is no better thing to do?

Minimum Complexity theory is n, then to achieve it?

We look at the following piece of code:

 

. 1 inline void pre_ () {
 2      for ( int i = 2 ; i <= n-; i ++) PP [i] = . 1 ; PP [ . 1 ] = 0 ; // PP to bool array, recording the digital whether or not i is a prime number later, before the screen we default 2 are both prime numbers
 . 3      for ( int I = 2 ; I <= n-; I ++ ) {
 . 4          IF (PP [I]) prime [++ TOT] = I; // If a number is a prime number , he put into the prime array
 . 5          for ( int J = . 1 ; J <&& prime TOT = [J] * I <= n-; J ++ ) {          
 . 6              PP [I * prime [J]] = 0; // sieve
 . 7              IF ((I% Prime [J])!) BREAK ; // key linear optimization to achieve the object
 8          }
 9      }
 10 }

 

Why it is linear it?

We only need to prove two things:

1, each composite number will be screened out

2, each composite number will only be screened out by a sieve

 

We Each number is combined decomposition A2 * ... * * A1 A n- form. (Wherein A-A1 n- are prime numbers, A1 <A2 <... <A n- )

For 1: when i is A3 * ... * * A2 A n- time, prime [j] is a1, the number will be screened out

For 2: When the prime [j] = AX (! = X. 1), I = A1 * ... * A X. 1- * A X +. 1 * ... * A n- , since when the prime [j] = it will break out of the loop when a1, and a1 <ax, so it can not satisfy j prime [j] = ax, so that a number of other opportunities for the screen does not exist.

Is proved

 

So we have a number of prime method of screening a minimum of complexity theory it!

Guess you like

Origin www.cnblogs.com/zub23333/p/11495648.html