首页 > 其他 > 详细

LeetCode(204):Count Primes

时间:2016-03-05 20:26:19      阅读:101      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!