*204. Count Primes (siecing prime)

本文介绍了一种有效的算法来计算小于非负整数n的质数数量。通过使用辅助数组进行筛选,避免了重复计算,并提供了详细的实现代码。示例中输入为10时,输出正确结果4,即2、3、5、7这四个质数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 

Solution2: ssieving: need a helping array with false initialization: false(prime) true(non- prime), inner loop: only set the multiple of prime.

class Solution {
    int res = 0;
    //solution 1: fun: check each unmber n * (n)
    //seieve solution: 2,3,5,7,11,13
    public int countPrimes(int n) {
        // 2: 1 3: 2 4: 2  ,5 :3 ....
        boolean[] aux = new boolean[n+1]; //all false (prime)
        for(int i = 2; i <n; i++){//i: number in n
            if(aux[i] == false) res++;
            if(aux[i] == true) continue; //pass the non -prime question: 2 and 4 have the same multiple??
            //sieving the number is multiple of this target nuber : aux[i]
            for(int j = 2; j*i <n; j++){
                aux[j*i] = true;
            } 
        }
        return res;
    }
    //time: i = 2 :n/2
    //      i = 3 : n/3 or smaller
    //    sum(n/i) : i is prime : n*sum(1/i) = n*(lg(lgn))
}

 

Solution 2:  is prime function

 

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.

转载于:https://www.cnblogs.com/stiles/p/leetcode204.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值