[leetcode]计数质数(Count Primes)

计数质数(Count Primes)

统计所有小于非负整数 的质数的数量。

示例:

输入: 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;
    }
};

把判断方法写在外面会方便很多

猜你喜欢

转载自blog.csdn.net/gcn_Raymond/article/details/86546193
今日推荐