[LeetCode 解题报告]204. 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 res = 0;
        for (int i = 2; i < n; i ++) {
            res += isPrimes(i);
        }
        return res;
    }
    
    static bool isPrimes(int n) {
        if (n <= 3) {
            return n > 1;
        }
        
        if (n % 6 != 1 && n % 6 != 5) {
            return false;
        }
        
        for (int i = 5; i*i <= n; i += 6) {
            if (n % i == 0 || n % (i + 2) == 0) {
                return false;
            }
        }
        return true;
    }
};
发布了467 篇原创文章 · 获赞 40 · 访问量 45万+

猜你喜欢

转载自blog.csdn.net/caicaiatnbu/article/details/104163289