Count Primes Below N
Write the code, see it run, pass the checks.
The problem
- medium
- Code
Write countPrimes(n): return how many prime numbers are less than n, not counting n itself. n is a whole number from 0 to 10,000,000. A prime is a whole number above 1 whose only divisors are 1 and itself, so there are none below 3 except 2. For example, countPrimes(10) is 4, for 2, 3, 5 and 7. The checks include n = 10,000,000, so testing each number for divisors one by one is too slow: cross out the multiples of each prime instead, the Sieve of Eratosthenes, keeping the marks in a Uint8Array rather than a plain array.
Your code must pass
- Counts the primes below small numbers
- Returns 0 when n is 2 or less
- Doesn't count n itself
- Is fast enough for n = 10,000,000