Count Primes
Posted amazingzoe
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Count Primes相关的知识,希望对你有一定的参考价值。
Description:
Count the number of prime numbers less than a non-negative number, n.
1 class Solution { 2 public: 3 int countPrimes(int n) { 4 vector<bool> primes(n, true); 5 6 // label all non-prime numbers 7 for (int i = 2; i < n; i++) { 8 if (!primes[i]) continue; 9 int count = 2; 10 while (count * i <= n) { 11 primes[(count++) * i] = false; 12 } 13 } 14 15 // count how many primes in the array 16 int result = 0; 17 for (int i = 2; i < n; i++) { 18 if (primes[i]) result++; 19 } 20 return result; 21 } 22 };
以上是关于Count Primes的主要内容,如果未能解决你的问题,请参考以下文章