[leetcode] Count Primes
Count Primes
Description:
Count the number of prime numbers less than a non-negative number, n
References:
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Have you met this question in a real interview?
class Solution { public: int countPrimes(int n) { vector<int> a(n); for(int i=0; i<n; i++) a[i] = i; for(int i=1; i * 2<= n; i++) { if(i == 1) { a[i] = 0; continue; } for(int j = i + i; j < n; j += i) { if(a[j] != 0) a[j] = 0; } } int count = 0; for(int i=0; i<n; i++) { cout << a[i] << " "; if(a[i] != 0) { count++; } } cout << endl; return count; } };