LeetcodeCount Primes

Posted wuezs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetcodeCount Primes相关的知识,希望对你有一定的参考价值。

题目链接:https://leetcode.com/problems/count-primes/

题目:

Description:

Count the number of prime numbers less than a non-negative number, n.

思路:

埃拉托色尼选筛法

算法:

public int countPrimes(int n) {  
        boolean c[] = new boolean[n];  
        for (int i = 2; i * i < n; i++) {  
            if(!c[i]){  
                for (int j = i+i; j < n; j += i) {  
                    if(!c[j])  
                        c[j] = true;  
                }  
            }  
        }  
        int count = 0;  
        for (int i = 2; i < n; i++) {  
            if (!c[i])  
                count++;  
        }  
        return count;  
    }  


以上是关于LeetcodeCount Primes的主要内容,如果未能解决你的问题,请参考以下文章

LeetcodeCount Numbers with Unique Digits

LeetcodeCount of Smaller Numbers After Self

LeetcodeCount of Smaller Numbers After Self

LeetcodeCount of Smaller Numbers After Self

LeetcodeCount Numbers with Unique Digits(计算各个位数不同的数字个数)

#Leetcode# 204. Count Primes