首页 > 其他 > 详细

LeetCode--Count Primes

时间:2015-05-18 10:30:51      阅读:104      评论:0      收藏:0      [点我收藏+]

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

1.常规思路(计算复杂度为O(n*sqrt(n))),提交后超时。

public static boolean isPrime(int m){
        boolean flag = true;
        for(int i=2; i<=Math.sqrt(m); i++){
            if(m % i == 0){
                flag = false;
                break;
            }
        }
        return flag;
    }
    
    
    public static int countPrimes(int n) {
        if(n<=2)
            return 0;
        else{
            int count = 1;
            for(int i=3; i<n; i++){
                if(isPrime(i))
                    count++;
            }
            return count;
        }
    }

2.只是统计小于n的素数的个数,则设置一个boolean型的数组,每次将一个素数的倍数设置为非素数,最后遍历一遍数组即可。

 public int countPrimes(int n) {
       boolean[] a = new boolean[n];
        for(int i=2; i*i<n; i++){
            if(!a[i]){//如果a[i]是素数
                for(int j=2; i*j<n; j++){
                    a[i*j] = true;
                }
            }
        }
        int count = 0;
        for(int i=2; i<n; i++){
            if(a[i] == false)
            {    count++;
            }
        }
        return count;
    }

 

LeetCode--Count Primes

原文:http://www.cnblogs.com/little-YTMM/p/4511195.html

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