Count Primes LeetCode solution in Python

1
class Solution:
2
def countPrimes(self, n: int) -> int:
3
# Prerequisite:
4
# What is prime number. What are they just the starting.
5

6
truth = [
7
True
8
] * n # making a list of lenght n. And keep all the values as True.
9
if n < 2: # as 0 & 1 are not prime numbers.
10
return 0
11
truth[0], truth[1] = (
12
False,
13
False,
14
) # as we added True in the truth list. So will make false for ) & 1 as they are not prime numbers.
15

16
i = 2 # As we know 0 & 1 are not prime.
17
while (
18
i * i < n
19
): # why we are doing it as i*i here is bcz lets say 5*2 = 10 is divisble by 2 as well as 5 so if 10 is already removed why to traverse a value which is already travered once. so in case of n=5 - 5<5. CONCLUSION : i<sqrt(n)
20
# why we are running the loop till n is bcz question says " prime numbers that are strictly less than n".
21
if truth[i] == True:
22
for j in range(
23
i * i, n, i
24
): # if we have mutiple of a number in the range of n, we have to remove them as they can be prime. i.e 2 is prime, but its multiple in n = 10 are 4,6,8 they cant be prime. So we will make them false(means not a prime).
25
truth[j] = False
26
i += 1 # increasing our iterator.
27
return truth.count(True) # will count true value

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0