【算法作业7】LeetCode 204. Count Primes

204. Count Primes

Description:

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

Hint:

  1. Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better?

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

题解:

本题是求小于一个非负整数n的所有质数的数目。第一反应想到的就是最简单粗暴的写一个判断质数的isPrime函数,然后对所有小于n的整数进行判断。但这种算法的复杂度为O(n²),肯定有时间限制不能通过。于是我们可以使用埃拉托色尼筛法,算法的主要思想就是让它在判断一个数为质数的同时,把它所有的倍数都设置为不是质数,这样就可以大大减少循环的次数。首先设置了一个vector来存放其下标对应的数字是否为质数并将除了0和1以外的其他元素设为true,在第一次循环的时候只需要循环到根号n,在这个循环中将每一个质数的倍数设为false即可。下面这幅图是从维基百科埃拉托色尼筛法中复制过来的,非常生动形象地诠释了算法的思想。



代码:

#include <cmath>
class Solution {
public:
    int countPrimes(int n) {
        vector<bool> primes;
        if (n == 0)
            primes.push_back(false);
        else
        {
            for (int i = 0; i < n; i++)
            {
                primes.push_back(true);
            }
            primes[0] = false;
            primes[1] = false;
        }
        for (int i = 0; i < sqrt(n); i++)
        {
            if (primes[i] == true)
            {
                for (int j = i * i; j < n; j += i)
                {
                    primes[j] = false;
                }
            }
        }
        int count = 0;
        for (int i = 0; i < n; i++)
        {
            if (primes[i])
                count++;
        }
        return count;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值