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

[LeetCode] 204. Count Primes

时间:2018-09-26 00:12:10      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:return   tput   自学   row   put   desc   题意   clear   etc   

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

标签:return   tput   自学   row   put   desc   题意   clear   etc   

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

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