LeetCode: Count Primes(计算n以内素数个数:高效算法)

LeetCode: Count Primes(计算n以内素数个数:高效算法)


Description:

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


A prime number is a natural number that has exactly two distinct natural number divisors: 1 and itself.
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity
埃拉托色尼筛选法:Sieve of Eratosthenes。
时间复杂度:O(n log log n)。
下面是图示过程,还有leetcode上hint用java编写的。

LeetCode: Count Primes(计算n以内素数个数:高效算法)_第1张图片

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*iif(!isPrime[i]) continue;
            //填表起点i*i,如3*3,因为3*2已填,步长+i
            for(int j=i*i;jfalse;
            }
        }
        int count=0;
        for(int i=2;iif(isPrime[i])  ++count;
        }
        return count;
    }
};

别人代码用的i*i与n比较,值得学习: Loop’s ending condition is i * i < n instead of i < sqrt(n) to avoid repeatedly calling an expensive function sqrt().

你可能感兴趣的:(leetcode)