Problem
Given an integern, return the number of prime numbers that are strictly less than n.
Examples
Constraints
- 0 <= n <= 5 * 10<sup>6</sup>
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 204 with 18 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 204 # by problem number
lcpy gen -s count_primes # by problem name
n, return the number of prime numbers that are strictly less than n.
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Input: n = 0
Output: 0
Input: n = 1
Output: 0
class Solution:
# Time: O(n log log n)
# Space: O(n)
def count_primes(self, n: int) -> int:
if n < 3:
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 multiple in range(i * i, n, i):
is_prime[multiple] = False
return sum(is_prime)
| Time | Space |
|---|---|
| O(n log log n) | O(n) |