计数质数(Count Primes)
统计所有小于非负整数 n 的质数的数量。
示例:
输入: 10 输出: 4 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
原题链接:https://leetcode-cn.com/problems/count-primes/
题解:
bool IsP(int m)
{
int i, j;
if(m < 2)
return true;
j = (int)sqrt(m);
for(i = 2; i <= j; i++)
if( m%i == 0)
return false;
return true;
}
class Solution {
public:
int countPrimes(int n) {
int num=0;
for(int h=2;h<n;h++)
{
if(IsP(h))
num++;
}
return num;
}
};
把判断方法写在外面会方便很多