1. 程式人生 > >#Leetcode# 204. Count Primes

#Leetcode# 204. Count Primes

n) code ret tps target rim HERE n-n ++

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;
    }
};

  

#Leetcode# 204. Count Primes