Count Primes

Count Primes

问题:

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

思路:

  计算质数的方法:http://en.wikipedia.org/wiki/Prime_number

我的代码:

public class Solution {
    public int countPrimes(int n) {
        int count=0;
        boolean[] nums = new boolean[n];
        for(int i=2; i<nums.length; i++){
            if(!nums[i]){
                count++;
                for(int j=2*i; j<nums.length; j=j+i){
                        nums[j] = true;
                }
            }
        }
        return count;
    }
}
View Code

学习之处:

  • 计算质数的方法
  • 如何计算质数的数量,代码简单而且有效

posted on 2015-05-06 11:28  zhouzhou0615  阅读(127)  评论(0编辑  收藏  举报

导航