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

leetcode : Count Primes

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