LeetCode: 204. Count Primes

LeetCode: 204. Count Primes

题目描述

Count the number of prime numbers less than a non-negative number, n.

Example:

Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

解题思路

首先统计素数表,然后统计素数 表中的内容。

AC 代码

class Solution 
{
public:
    int countPrimes(int n)
    {
        vector<bool> isPrime(n, true);
        isPrime[0] = false;
        isPrime[1] = false;
        isPrime[2] = true;
        
        // 标记非素数
        for(int i = 2; i < n; ++i)
        {
            if(isPrime[i] == false) continue;
            
            int notPrime = i*2;
            while(notPrime < n)
            {
                isPrime[notPrime] = false;
                notPrime += i;
            }
        }
        
        // 统计素数的数量
        int cnt = 0;
        for(int i = 0; i < n; ++i)
        {
            cnt += isPrime[i];
        }
        
        return cnt;
    }
};
全部评论

相关推荐

点赞 评论 收藏
分享
10-09 17:17
已编辑
门头沟学院 Java
活泼的代码渣渣在泡池...:同学你好,我也是学院本,后天要面这个亚信科技,是实习,请问问题都啥样呀,我项目就做了网上的,这是第一次面试
投递多益网络等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务