Member-only story
Count the number of Prime Numbers (LeetCode Problem-Solving—5)
The problem is to count the number of Prime Numbers which should be less than a given integer n
. Prime Number: is a number which is greater than 1
, that is divisible by only 1
and itself
.
My articles are open for everyone; non-member readers can read the article by clicking this Friend link.
1 — Approach
To solve this problem efficiently given the constraints: 0 <= n <= 5 * 106
, the Sieve of Eratosthenes algorithm is the best approach. This algorithm helps find all prime numbers up to a given number n
in O(n log log n)
time.
2 — Algorithm: Sieve of Eratosthenes
1. Initialize a boolean Array:
- Create a boolean array
isPrime
of sizen
and initialize all elements totrue
. isPrime[i]
will indicate whetheri
is a prime number.- Set
isPrime[0]
andisPrime[1]
to false (since0
and1
are not primes)
2. Mark Multiples of Primes:
- Start witht the Prime number
2
. For every numberp
, mark all its multiples as non-prime (i.e., setisPrime[j] = false
for allj = p * p, p * p + p, …, n
).
Question: — Why
2
is a Prime Number, but…