首页 > 代码库 > 【LeetCode】204. Count Primes 解题小结

【LeetCode】204. Count Primes 解题小结

 题目:

Description:

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

这个题目有提示,计算素数的方法应该不用多说。

class Solution {public:    int countPrimes(int n) {        vector<bool> isPrime;        for (int i = 0; i < n; ++i){            isPrime.push_back(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 cnt = 0;        for (int i = 2; i < n; ++i){            if (isPrime[i]) cnt++;        }        return cnt;    }};

 

【LeetCode】204. Count Primes 解题小结