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

Count Primes

时间:2016-10-08 13:51:47      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

Description:

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

//TLE
class Solution {
private:
    bool isPrime(int n) {
        if (n <= 1)
            return false;
        for (int i = 2; i * i <= n; i++) {
            if (n % i == 0)
                return false;
        }
        return true;
    }
public:
    int coutPrimes(int n) {
        int count = 0;
        for (int i = 1; i < n; i++) {
            if (isPrime(i))
                count++;
        }
        return count;
    }
};

//筛数法
class Solution2 {
public:
    int countPrimes(int n) {
        if (n <= 1) return 0;
        bool* IsPrime = new bool[n];
        for (int i = 2; i < n; i++) {
            IsPrime[i] = true;
        }

        for (int i = 2; i * i < n; i++) {
            if (!IsPrime[i])
                continue;
            for (int j = i * i; j < n; j += i) {
                IsPrime[j] = false;
            }
        }
        int count = 0;
        for (int i = 2; i < n; i++) {
            if (IsPrime[i])
                count++;
        }
        return count;
    }
};

 

Count Primes

标签:

原文地址:http://www.cnblogs.com/wxquare/p/5937877.html

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