LeetCode Top Interview Questions 204. Count Primes (Java版; Easy)

welcome to my blog

LeetCode Top Interview Questions 204. Count Primes (Java版; Easy)

题目描述
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.
第一次做; 这个计算[2,n)上素数的个数的算法叫作埃拉托色尼筛选法(Sieve of Eratosthenes); 算法思想如图

埃拉托色尼筛选法(the Sieve of Eratosthenes)简称埃氏筛法,是古希腊数学家埃拉托色尼(Eratosthenes 274B.C.~194B.C.)提出的一种筛选法。 是针对自然数列中的自然数而实施的,用于求一定范围内的质数

class Solution {
    public int countPrimes(int n) {
        if(n<2)
            return 0;
        boolean[] isPrime = new boolean[n];
        Arrays.fill(isPrime, true);
        int count = 0;
        for(int i=2; i<n; i++){
            if(isPrime[i]==true){
                count++;
                //i的倍数就不是素数了
                for(int j=2; j*i<n; j++){
                    isPrime[j*i] = false;
                }
                /*
                内层循环也可以这么写, 快1ms
                for(int j=2*i; j<n; j=j+i){
                    isPrime[j] = false;
                }
                */
            }
        }
        return count;
    }
}
LeetCode题解, 大循环执行sqrt(n)次, 就能将notPrime填写完整! 不过这样就不能在大循环中计数了, 需要单独写个循环遍历notPrime用来统计质数的个数
public int countPrimes(int n) {
    if(n <=1 ) return 0;
    
    boolean[] notPrime = new boolean[n];        
    notPrime[0] = true; 
    notPrime[1] = true; 

    for(int i = 2; i < Math.sqrt(n); i++){
        if(!notPrime[i]){
            for(int j = 2; j*i < n; j++){
                notPrime[i*j] = true; 
            }
        }
    }
    
    int count = 0; 
    for(int i = 2; i< notPrime.length; i++){
        if(!notPrime[i]) count++;
    }
    return count; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值