首页 > 其他 > 详细

leetcode : Count Primes

时间:2015-04-29 08:41:17      阅读:262      评论:0      收藏:0      [点我收藏+]

Description:

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



[思路]

素数不能被比它小的整数整除, 建一个boolean 数组, 从2开始, 把其倍数小于N的都删掉.

注意 inner loop从i开始, 比i小的会在以前就被check过.


[CODE]

public class Solution {
    public int countPrimes(int n) {
     //2,3,5,7,11,13,17 
     //20  5
     //init check  n
     boolean[] a = new boolean[n];
     for(int i=2; i*i<n; i++) {
        if(!a[i]) {
            for(int j=i; i*j<n; j++) {
                a[i*j] = true;
            }
        }
     }
     int c=0;
     
     for(int i=2; i<n; i++) {
         if(a[i] == false) ++c;
     }
     return c;
    }
}


leetcode : Count Primes

原文:http://blog.csdn.net/xudli/article/details/45361471

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