LeetCode OJ:Count Primes(质数计数)
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 };
java版本的代码如下所示:
public class Solution { public int countPrimes(int n) { int [] prime = new int[n+1]; //这里其实用boolean更好,懒得改了 int count = 0; for(int i = 0; i < n+1; ++i){ prime[i] = i; } for(int i = 2; i < n+1; ++i){ if(prime[i] == -1) continue; else{ count++; for(int mul = 2; mul * i < n+1; ++mul){ prime[mul*i] = -1; } } } return count; } }