topic:
Count the number of all prime numbers less than the non-negative integer n. Example: Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10 , they are 2 , 3 , 5 , 7 .
Problem solving ideas:
Code:
class Solution { public: bool isPrime(int num) { if (num <= 1) return false; for (int i = 2; i*i <= num; ++i) { if (num%i == 0) return false; } return true; } int countPrimes(int n) { bool *isPrime = new bool[n]; for (int i = 2; i < n; ++i) { isPrime[i] = true; } for (int i = 2; i*i < n; ++i) { if (!isPrime[i]) continue; for (int j = i*i; j < n; j += i) { isPrime[j] = false; } } int count = 0; for (int i = 2; i < n; ++i) { if (isPrime[i]) count++; } return count; } };