forked from shijbian/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcount-primes.py
More file actions
33 lines (26 loc) · 713 Bytes
/
count-primes.py
File metadata and controls
33 lines (26 loc) · 713 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Time: O(n)
# Space: O(n)
# 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.
class Solution:
# @param {integer} n
# @return {integer}
def countPrimes(self, n):
if n <= 2:
return 0
is_prime = [True] * n
num = n / 2
for i in xrange(3, n, 2):
if i * i >= n:
break
if not is_prime[i]:
continue
for j in xrange(i*i, n, 2*i):
if not is_prime[j]:
continue
num -= 1
is_prime[j] = False
return num