首页 > 其他 > 详细

[LeetCode] 204. Count Primes

时间:2018-09-25 23:56:14      阅读:206      评论:0      收藏:0      [点我收藏+]

204. Count Primes



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

Example:

Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.


题意:找素数,找n以内有多少个素数
筛数法统计
class Solution {
    public int countPrimes(int n){
        if (n == 0 || n == 1 || n == 2)
            return 0;
        int[] num = new int [n];
        for (int i = 0; i < n; i++) {
            num[i] = i;
        }

        for (int i = 2; i < n; i++) {
            if (num[i] != 0) {
                for (int j = 2; j*i < n; j ++)
                    num[j*i] = 0;
            }
        }
        int sum = 0;
        for (int i = 0; i < n; i++) {
            if (num[i] != 0)
                sum ++;
        }
        return sum - 1;
    }
}

最快的算法应该是 6n那个,但是我不会,hhaha有兴趣的小伙伴可以自学一下

[LeetCode] 204. Count Primes

原文:https://www.cnblogs.com/Moriarty-cx/p/9704231.html

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