码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode(204):Count Primes

时间:2016-03-05 20:28:08      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
}

LeetCode(204):Count Primes

标签:

原文地址:http://www.cnblogs.com/Lewisr/p/5245582.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!