LeetCode(204):Count Primes

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

题意:求出小于n的数中质数的个数。

思路:可以先写出一个判断一个整数是否是质数的函数,然后在从1到n开始判断,但是通过不了,看了提示中的Sieve of Eratosthenes,可以根据它进行求解。

代码:

public class Solution {
    public int countPrimes(int n) {
    boolean[] isPrime = new boolean[n]; //定义一个数组
    for(int i=2;i<n;i++){
        isPrime[i] = true;
    } //初始化为True,初始化全为质数
    for(int i = 2;i*i<n;i++){  //然后从1到sqrt(n)
        if(!isPrime[i]) continue;  //如果不是质数则继续下一轮循环
        for(int j=i*i;j<n;j+=i){  //如果是质数,则其小于n的整数倍都不是质数,则设置为false,j+=i是计算j的整数倍
            isPrime[j] = false;
        }
    }
    int count =0;
    for(int i=2;i<n;i++){  //统计true的数量
        if(isPrime[i])count++;
    }
        return count;
    }
}
原文地址:https://www.cnblogs.com/Lewisr/p/5245582.html