Problem Statement
Givenan integer n, return the number of prime numbers that are
strictly less than n.
3.
Examples
Example 1:
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1
Output: 0
class Solution:
def countPrimes(self,n: int) -> int:
if n < 2:
return 0
is_prime = [True] * n
is_prime[0] = is_prime[1] = False
for i in range(2, int(n ** 0.5) + 1):
if is_prime[i]:
for j in range(i * i, n, i):
is_prime[j] = False
return sum(is_prime)
Python Solution
Initially set all numbers as Prime
Python's range() is exclusive at the
end, it stops before the upper limit.
6.
class Solution:
def countPrimes(self,n: int) -> int:
if n < 2:
return 0
is_prime = [True] * n
is_prime[0] = is_prime[1] = False
for i in range(2, int(n ** 0.5) + 1):
if is_prime[i]:
for j in range(i * i, n, i):
is_prime[j] = False
return sum(is_prime)
Walkthrough
0 1 2 3 4 5 6 7 8 9 10
n = 10
T T T T T T T T T T T
F F T T T T T T T T T
i = 2
√10 = 3
True
F F T T F T F T F T F
i = 3
F F T T F T F T F F F
Solution: 4
7.
Java Solution
class Solution{
public int countPrimes(int n) {
if (n < 2)
return 0;
boolean[] isPrime = new boolean[n];
for (int i = 2; i < n; i++)
isPrime[i] = true;
for (int i = 2; i * i < n; i++) {
if (isPrime[i]) {
for (int j = i * i; j < n; j += i)
isPrime[j] = false;
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i])
count++;
}
return count;
}
}