Skip to content

Commit 894a441

Browse files
authored
Added to CountPrimesUsingSieve.py
1 parent 99cf7d7 commit 894a441

1 file changed

Lines changed: 14 additions & 0 deletions

File tree

CountPrimesUsingSieve.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Python Sieve of Eratosthenes - https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
2+
# The idea of the sieve of Eratosthene is to start with the list of all integer starting at 2 up to the limit we want to compute.
3+
# A prime number is not the multiple of any number except 0, 1 and itself.
4+
# So a way to find all primes up to the limit is to remove all multiples of the primes we currently know of starting at 2.
5+
class Solution:
6+
def countPrimes(self, n: int) -> int:
7+
candidates = list(range(2,n))
8+
for idx, num in enumerate(candidates):
9+
if num is not None:
10+
for multiple in range(idx+num, len(candidates), num):
11+
candidates[multiple] = None
12+
return sum(1 for i in candidates if i is not None)
13+
14+
# This algorithm is good if you want preprocessed data of prime numbers. #SharingKnowledge #Hacktoberfest2020

0 commit comments

Comments
 (0)