标签:
Count the number of prime numbers less than a non-negative number, n.
计算小于n的质数的个数,当然就要用到大名鼎鼎的筛法了,代码如下,写的有点乱不好意思。
1 class Solution { 2 public: 3 int countPrimes(int n) { 4 vector<int> vtor(n + 1, 0); 5 vector<int> ret; 6 for (int i = 0; i <= n; ++i) 7 vtor[i] = i; 8 for (int i = 2; i < n; ++i){//边界条件注意 9 if (vtor[i] != -1){ 10 ret.push_back(vtor[i]); 11 int tmpPrime = vtor[i]; 12 for (int mul = 1; tmpPrime * mul <= n; mul++){ 13 vtor[tmpPrime * mul] = -1; 14 } 15 } 16 } 17 return ret.size(); 18 } 19 };
LeetCode OJ:Count Primes(质数计数)
标签:
原文地址:http://www.cnblogs.com/-wang-cheng/p/4857872.html