Leetcode and Wikipedia all have the sieve of Eratosthenes algorithm used to explain the problem.
The algorithm can find all prime numbers less than n in O (Nloglogn) time, and the spatial complexity is O (n).
With the increase of n, when space is limited, Wikipedia also proposes a segmented screening (segmented sieve) method to reduce the spatial complexity to O (n^0.5) in the case of constant time complexity.
The following code implements the general filtering (regular sieve) method:
Class Solution { Public:int CountPrimes(intN) {if(N <=1) {return 0; }BOOLPrime[n]; memset (Prime,true,sizeof(prime)); for(inti =2; I * i < n; + + i) {if(Prime[i] = =false) {Continue; } for(intj = i * I; J < N; J + = i) {Prime[j] =false; } }returnCount_if (prime+2, Prime+n, [] (BOOLPRIME)BOOL{returnPrime;}); }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 204. Count Primes