leetcode 204

本文介绍了两种计算小于非负整数n的质数数量的方法。解法一通过遍历和检查每个数是否为质数来计数;解法二采用埃拉托斯特尼筛法(Sieve of Eratosthenes),提高了效率。

题目描述:

Description:

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

 

解法一:

遍历从1-n的所有整数,查看是否为质数,是质数借助一个则将该整数存入一个容器中,判断一个数是否为质数,可以遍历在容器中且小于n的平方根的质数,如果n可以被符合条件的质数整除,则这个数不是质数。代码如下:

class Solution {
public:
    vector<int> prime_vec;
    
    bool isPrime(int n)
    {
        if (n<2)
            return false;
        else if (n == 2)
            return true;
        else if (n % 2 == 0)
            return false;
        else
        {
            int n_sqr = sqrt(n);
            for (int i = 0; prime_vec[i] <= n_sqr; i ++) {
                if(n % prime_vec[i] == 0)
                    return false;
            }
            return true;
        }
    }
    
    int countPrimes(int n) {
        int counter = 0;
        for (int i = 1; i < n; i ++) {
            
            if (isPrime(i)) {
                
                prime_vec.push_back(i);
                counter ++;
            }
        }
        
        for (auto i = prime_vec.begin(); i != prime_vec.end(); i ++) {
            cout << *i << endl;
        }
        return counter;
        
    }
};

 

 

解法二:

上述代码的执行效率不高,看了其他人的解题思路之后,豁然开朗,维基百科上有一个动态演示的效果图,算法思想名叫“晒数法”,连接如下:

https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

看了这个效果图我马上进行了自己的实现,代码如下:

class Solution {
public:
    int countPrimes(int n) {
        int counter = 0;
        if (n < 2)
            return counter;
        
        int upper = sqrt(n);
        vector<bool> flag_vec(n, false);
        int i = 2;
        while (i < n) {
            cout << i << endl;
            counter ++;
            if(i <= upper)
            {
                for (long long j = i * i; j < n; j += i)
                    flag_vec[j] = true;

            }
            
            ++ i;
            while (flag_vec[i] == true)
                ++ i;
            
        }
        
        return counter;
        
    }
};

 

 

可以很清楚地知道,解法二比解法一要好很多,因为在从小到大遍历的过程中,所有的数仅遍历一遍,这解法一虽然比暴力的O(n*n)的方法好一些,但是时间复杂度还是大于O(n)的,而晒数法的时间复杂度仅为O(n)。

转载于:https://www.cnblogs.com/maizi-1993/p/5931568.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值