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

LeetCode-Count Primes

时间:2016-09-14 01:58:04      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

Description:

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Analysis:

See hint in leetcode.

Solution:

public class Solution {
    public int countPrimes(int n) {
        if (n<=2) return 0;
        
        boolean[] marked = new boolean[n];
        
        for (int i=3;i*i<n;i+=2)
            if (!marked[i]){
                // i*i+(2*k+1)*i = i*(i+1+2k) is an even value because (i+1) is even.
                // We can skip all such number by increasing value by 2*i every time.
                for (int value = i*i;value<n;value+=2*i){
                    marked[value]=true;
                }
            }
            
        int count = 1;
        for (int i=3;i<n;i+=2)
            if (!marked[i]){
                count++;
            }
        return count;
    }
}

 

LeetCode-Count Primes

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/5870373.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!