Method 1: Enumeration
class Solution {
public:
bool isPrime(int x) {
for (int i = 2; i * i <= x; ++i) {
if (x % i == 0) {
return false;
}
}
return true;
}
int countPrimes(int n) {
int ans = 0;
for (int i = 2; i < n; ++i) {
ans += isPrime(i);
}
return ans;
}
};
Method 2: Tabulation ( 重点
)
- First set all numbers to prime numbers (marked as 1);
- From the first prime number 2 to n traverse, if the current number is prime, then result+1, and set the multiples of prime numbers to not prime numbers (marked as 0);
There are two sets of codes below. K is optimized starting from i. It is also possible to start from 2, but this is a bit repetitive (for example, a number x=2*i, this number is a multiple of i, which is also a multiple of 2, then This x has been set when i=2).
for(int k=i;(long long)i*k<n;k++){
isprime[i*k]=0;
}
class Solution {
public:
int countPrimes(int n) {
vector<int>isprime(n+1,1);
int result=0;
for(int i=2;i<n;i++){
if(isprime[i]==1){
result++;
for(int k=2;i*k<n;k++){
isprime[i*k]=0;
}
// for(int k=i;(long long)i*k<n;k++){
// isprime[i*k]=0;
// }
}
}
return result;
}
};
The weather is a bit cold these past two days, I feel like catching a cold