204_Count Primes
Count the number of prime numbers less than a non-negative number n.
Example:
Solution 1: brute force
Idea:
Loop over every number from 2 to
n-1
and check if it is prime.To check if a number
i
is prime, check if it is divisible by a number from 2 to the square root ofi
. If yes, it is not prime.Why use the square root of
i
? Because ifi
has a divisor other than 1 and itself, it must also have a divisor that is no greater than its square root.
Time complexity:
Space complexity:
Solution 2
Reference: Sieve of Eratosthenes https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Idea:
Exclude the multiples of primes
Only need to loop over from item 2 to square root of n
Time complexity:
Space complexity:
Last updated