-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path204.py
More file actions
40 lines (29 loc) · 1.14 KB
/
204.py
File metadata and controls
40 lines (29 loc) · 1.14 KB
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
34
35
36
37
38
39
40
'''
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.
Ref.
Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n).
Initially, let p equal 2, the first prime number.
Starting from p2, count up in increments of p and mark each of these numbers greater than or equal to p2 itself in the list. These numbers will be p(p+1), p(p+2), p(p+3), etc..
Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3.
https://www.geeksforgeeks.org/sieve-of-eratosthenes/
'''
# Eratosthenes’ method
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
_prime = [True]*n
_count = 0
for i in range(2,n):
if _prime[i] == True:
_count+=1
for j in range(i*i,n,i):
_prime[j] = False
return _count