Blog Archive

Wednesday, December 16, 2015

[LeetCode]Count Primes |

[LeetCode]Count Primes | 

题目描述:

Description:
Count the number of prime numbers less than a non-negative number, n
Hint: The number n could be in the order of 100,000 to 5,000,000.
References:
How Many Primes Are There? (https://primes.utm.edu/howmany.html)
Sieve of Eratosthenes (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)

题目大意:

统计小于非负整数n的素数的个数
提示:n的范围是100,000到5,000,000

参考文献:

一共有多少个素数?(https://primes.utm.edu/howmany.html)
埃拉托斯特尼筛法 (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)

解题思路:

见埃拉托斯特尼筛法。

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
起初Python的时间限制过于严格,采用Python解题对于测试样例5000000总是返回Time Limit Exceeded,后来管理员放宽了Python的时限。

No comments:

Post a Comment