#Leetcode# 204. Count Primes
https://leetcode.com/problems/count-primes/
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
代码:
class Solution {
public:
int countPrimes(int n) {
int ans = 0;
if(n == 0 || n == 1)
return 0;
for(int i = 2; i < n; i ++)
if(isPrime(i)) ans ++;
return ans;
}
bool isPrime(int x) {
for(int i = 2; i * i <= x; i ++)
if(x % i == 0) return false;
return true;
}
};

浙公网安备 33010602011771号