Leetcode 204. Counting prime numbers
Question stem
Count all the prime numbers less than the non-negative integer n.
Example 1:
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, and they are 2, 3, 5, 7.
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1
Output: 0
Tip:
0 <= n <= 5 * 106
answer
Linear sieve:
* Flag bit isntPrime, prime number is false, prime number list primeList
* Iterate from 2 to n, when a number flag bit is false, add it to the prime number list
* Regardless of the flag bit of a certain number, iterate through it once Prime number list, to the product of the prime number and the current number, mark the position of the product number as true, if the current number is a multiple of the prime number, terminate the traversal of the list of prime numbers
* When i% j == 0, it means that i is j The multiple of i, that is, the current i multiplied by other prime numbers, can be expressed as: j * (other prime numbers * multiples), and this result will definitely appear in i in the subsequent traversal of i increase. So in order to avoid repeated time-consuming, pop up when i% j == 0
class Solution {
public:
int countPrimes(int n) {
int ans = 0;
vector<bool> isntPrime(n+1,false);
vector<int> primeList;
if(n <= 2){
return 0;
}
for(int i = 2 ; i < n ; ++i){
if(!isntPrime[i]){
ans++;
primeList.push_back(i);
}
for(auto j : primeList){
if(j * i >= n ){
break;
}
isntPrime[j * i] = true;
if(i % j == 0){
break;
}
}
}
return ans;
}
};