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

Count Primes

时间:2016-02-28 15:16:42      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

题目:

Description:

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

cpp:

class Solution {
public:
    int countPrimes(int n) {
        bool isPrime[n];
        for (int i = 0; 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;
    }
};

python:

class Solution:
    # @param {integer} n
    # @return {integer}
    def countPrimes(self, n):
        isPrime = [True] * max(n, 2)
        isPrime[0], isPrime[1] = False, False
        x = 2
        while x * x < n:
            if isPrime[x]:
                p = x * x
                while p < n:
                    isPrime[p] = False
                    p += x
            x += 1
        return sum(isPrime)

 

Count Primes

标签:

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

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