Euler sieve (for prime numbers)
Linear sieve with an O (n) degree of complexity. Compared to the composite, it is more efficient to repeat the labeling of the labeled markers. The Euler sieve decomposes the composite into the form of (min factorization * a composite) and determines whether the current composite has been marked by a minimum of factorization.
const int MAXN = 101; Table length
int PRIME[MAXN], pnum = 0; Prime record Prime, pnum number of elements
bool P[maxn] = {false}; P record whether the current number is sieved to
void Eulersieve (int n) ///lookup record 2-n of the primes
{for
(int i = 2; I <= n; i++)
{
if (P[i] = = False) //If not sifted, then prime
prime[pnum++] = i;
for (j = 0; J < Pnum; J + +)
{
if (i * prime[j] > N) //Jump out of break when the composite to be marked is out of range
;
P[i * Prime[j]] = true; Mark multiples of the number of recorded primes
if (i% prime[j] = = 0) //Key step break;}}
}
The difficulty of Euler sieve is to understand if (i% prime[j] = = 0) This step, when I is prime[j] integer times, remember m = i/prime[j], then I * prime[j+1] can become (M * prime[j+1]) * prime [j], this indicates that I * prime[j+1] is an integer multiple of prime[j], does not need to be marked (after which will be prime[j] * A number of marks), for prime[j+2] and after the prime of the same way, jump directly out of the loop, so that the repetition of the tag is avoided.