首页 > 其他 > 详细

LeetCode 204. Count Primes

时间:2016-07-09 17:46:01      阅读:128      评论:0      收藏:0      [点我收藏+]

Problem: https://leetcode.com/problems/count-primes/

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

 

Thought:

SieveofEratosthenes 

 

Code C++:(meet Runtime Error on test case 150000, which I haven‘t found the reason)

class Solution {
public:
    int countPrimes(int n) {
        if (n <= 1) {
            return 0;
        }
        int nums[n];
        for (int i = 0; i < n; i++) {
            nums[i] = 1;
        }
        nums[0] = 0;nums[1] = 0;
        for (int i = 2; i * i <= n; i++) {
            if (!nums[i]) {
                continue;
            }
            for (int j = 2; i * j < n; j++) {
                nums[i * j] = 0;
            }
        }
        int solve = 0;
        for (int i = 0; i < n; i++) {
            solve += nums[i];
        }
        return solve;
    }
};

 

LeetCode 204. Count Primes

原文:http://www.cnblogs.com/gavinxing/p/5656116.html

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