欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【编程题】 Count Primes(计算n以内素数个数:高效算法)

程序员文章站 2024-03-14 20:54:17
...

【编程题】 Count Primes(计算n以内素数个数:高效算法)

代码:

class Solution {
public:
    int countPrimes(int n) {
        if(!n||n==1)  return 0;
        vector<bool> isPrime(n,true);
        // Loop's ending condition is i * i < n instead of i < sqrt(n)
        // to avoid repeatedly calling an expensive function sqrt().
        for(int i=2;i*i<n;++i)
        {
            if(!isPrime[i]) continue;
            //填表起点i*i,如3*3,因为3*2已填,步长+i
            for(int j=i*i;j<n;j+=i)
            {
                isPrime[j]=false;
            }
        }
        int count=0;
        for(int i=2;i<n;++i)
        {
            if(isPrime[i])  ++count;
        }
        return count;
    }
};