[Leetcode]204. Count Primes

来源:互联网 发布:成都生活家装饰 知乎 编辑:程序博客网 时间:2024/04/30 15:30

Description:

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

class Solution {public:    int countPrimes(int n) {        bool isPrime[n];        for (int i = 2; i < n; ++i)            isPrime[i] = true;        for (int i = 2; i * i < n; ++i) {            if (!isPrime[i])                continue;            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;    }};

0 0