质数是指在大于1的自然数中,除了1和它本身以外不再有其他因数的自然数。
如果一个数不是素数是合数, 那么一定可以由两个自然数相乘得到, 其中一个大于或等于它的平方根,一个小于或等于它的平方根,并且成对出现。所以判断n是不是质数,只需要判断2 ~ sqrt(n)之间的数字能不能被n整除就可以了。
相对暴力
//质数是指在大于1的自然数中,除了1和它本身以外不再有其他因数的自然数。
class Solution {
public:
int countPrimes(int n) {
int res = 0;
if(n > 2) ++res;//2是唯一的偶数质数
for(int i = 3; i < n; i += 2){//只考虑奇数
if(isPrime(i)) ++res;
}
return res;
}
bool isPrime(int n){
for(int i = 3; i * i <= n; i += 2){//偶数不用考虑
if(n%i == 0) return false;
}
return true;
}
};
优化
可以看这个题解的解释:
如何高效判定、筛选素数 - 计数质数 - 力扣(LeetCode)
class Solution {
public:
int countPrimes(int n) {
int res = 0;
vector<int> sign(n, 1);
for(int i = 2; i < n; ++i){
if(sign[i] == 1){
++res;
for(int j = i+i; j < n; j += i) sign[j] = 0;
}
}
return res;
}
};
稍作优化:
//质数是指在大于1的自然数中,除了1和它本身以外不再有其他因数的自然数。
class Solution {
public:
int sign[5000010];
int countPrimes(int n) {
int res = 0;
if(n >= 3) ++res;
for(int i = 3; i < n; i += 2){
if(sign[i] == 0){
++res;
for(int j = i+i; j < n; j += i) sign[j] = 1;
}
}
return res;
}
};