204. Count Primes(计算素数的个数)

problems:

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.

tip:

求在n范围内,素数的个数.

solutions:

1.直接暴力循环法,思路清晰,但是复杂度高.不可以AC

class Solution {
public:
    bool isprime(int n)
    {
        for(int i=2;i<n;i++)
            if(n%i==0)
                return false;
        return true;
    }
    int countPrimes(int n) {
        int m=0;
        for(int i=2;i<n;i++)
        {
            if(isprime(i))
                m++;
        }
        return m;
    }
};

2.https://www.cnblogs.com/grandyang/p/4462810.html 埃拉托斯特尼筛法
从2开始遍历到根号n,先找到第一个质数2,然后将其所有的倍数全部标记出来,然后到下一个质数3,标记其所有倍数,一次类推,直到根号n,此时数组中未被标记的数字就是质数。

class Solution {
public:
    int countPrimes(int n) {
      vector<bool> prime(n,true);
        int res = 0;
        for(int i=2;i<n;i++)
        {
            if(prime[i]) ++res;
            for(int j=2;i*j<n;j++)
            {
                prime[i*j]=false;
            }
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值