首页 > 其他 > 详细

LeetCode-Count Primes

时间:2016-09-14 01:55:51      阅读:194      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!