LeetCode[204] Count Primes

来源:互联网 发布:linux diff命令的功能 编辑:程序博客网 时间:2024/06/10 14:24

Description:

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

class Solution {public:int countPrimes(int n) {vector<bool> isPrime(n, true);isPrime[0] = isPrime[1] = false;int sq = sqrt(n);for (int i = 2; i <= sq; ++i) {if (isPrime[i]) {for (int j = i * i; j < n; j += i)isPrime[j] = false;}}int cnt = 0;for (auto i : isPrime) {if (i)++cnt;}return cnt;}};

0 0