题目描述:
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)
解题思路:
见埃拉托斯特尼筛法。
另请参阅:http://open.163.com/movie/2012/10/0/6/M99VJKUHC_M9ENDUB06.html
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)
起初Python的时间限制过于严格,采用Python解题对于测试样例5000000总是返回Time Limit Exceeded,后来管理员放宽了Python的时限。
下面附本题目采用Java解答的代码。
Java代码:
public class Solution {
public int countPrimes(int n) {
boolean notPrime[] = new boolean[n + 2];
notPrime[0] = notPrime[1] = true;
for (int i = 2; i * i < n; i++) {
if (!notPrime[i]) {
int c = i * i;
while (c < n) {
notPrime[c] = true;
c += i;
}
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
if (!notPrime[i])
ans ++;
}
return ans;
}
}
本文链接:http://bookshadow.com/weblog/2015/04/27/leetcode-count-primes/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。