Sieve of Eratosthenes-Eratosthenes sieve, referred to as the sieve.
Idea: give the range of values to sieve N, find the prime number within . First use 2 to sift, that is, 2 left, the number of 2 is removed, and then the next prime, that is, 3 sieve, 3 left, the multiples of 3 is removed, then the next prime number of 5 sieve, 5 left, the multiples of 5 are removed; Keep repeating ... until it is less than equals.
As follows:
Example: A problem with searching for prime numbers on Leetcode (https://leetcode.com/problems/count-primes/).
Question:Count The number of prime numbers less than a non-negative number, n
PS: When the N=1500000,leetcode evaluation is 58ms, the operating efficiency is good in C + +.
int countprimes (int n) { bool isprimes[n]; int primesnum=0; for (int i=2; i<n; i++) isprimes[i]=true; Remove the times of primes. for (int i=2; i<=sqrt (n), i++) if (Isprimes[i]) for (int j=2; j*i<=n; j + +) Isprimes[j*i]=false; The count of primes. for (int i=2; i<n; i++) if (Isprimes[i]) primesnum++; return primesnum;}
Efficient search for prime--sieve of Eratosthenes