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

Count Primes

时间:2015-04-28 22:39:09      阅读:164      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!