题目大意
204. Count Primes
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
题目大意:
统计小于非负整数n的素数的个数
提示:n的范围是100,000到5,000,000
解题思路
参考文献:
伪代码
Input: an integer n > 1.
Let A be an array of Boolean values, indexed by integers2to n,
initially all set to true.for i = 2, 3, 4, ..., notexceeding √n:if A[i] istrue:for j = i2, i2+i, i2+2i, i2+3i, ..., notexceeding n:
A[j] :=false.
Output: all i such that A[i]is true.
Python解法
起初Python的时间限制过于严格,采用Python解题对于测试样例5000000总是返回Time Limit Exceeded,后来管理员放宽了Python的时限。
classSolution(object):defcountPrimes(self, n):""":type n: int
:rtype: int"""is_prime= [True] * max(n, 2)
is_prime[0], is_prime[1] =False, False
x= 2
while x * x
p= x *xwhile p
is_prime[p]=False
p+=x
x+= 1
returnsum(is_prime)defcountPrimes_v0(self, n):""":type n: int
:rtype: int"""is_prime= [True] * max(n, 2)
is_prime[0], is_prime[1] =False, Falsefor x in range(2, int(n ** 0.5) + 1):ifis_prime[x]:
p= x *xwhile p
is_prime[p]=False
p+=xreturn sum(is_prime)
Java解法
public classSolution {
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
notPrime[c]=true;
c+=i;
}
}
}
int ans=0;for (int i = 0; i < n; i++) {if(!notPrime[i])
ans++;
}returnans;
}
}
参考:http://bookshadow.com/weblog/2015/04/27/leetcode-count-primes/