首页 > 其他 > 详细

Count Primes

时间:2015-04-28 22:38:20      阅读:229      评论:0      收藏:0      [点我收藏+]

Description:

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

References:

How Many Primes Are There?

Sieve of Eratosthenes

 

 由于一个合数总是可以分解成若干个质数的乘积,那么如果把质数(最初只知道2是质数)的倍数都去掉,那么剩下的就是质数了。

public class Solution {
    public int countPrimes(int n) {
        boolean[] A = new boolean[n+1];
        for(int i=2;i*i<n;i++) {
            if(!A[i]) {
                int j = 0;
                while(i*i+j<=n) {
                    A[i*i+j] = true;
                    j = j+i;
                }
            }
        }
        int count = 0;
        for(int j=2;j<n;j++) {
            if(!A[j])
            count++;
        }
        return count;
    }
}

 

技术分享

Count Primes

原文:http://www.cnblogs.com/mrpod2g/p/4464073.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!