Count Primes | LeetCode 204 (Sieve of Eratosthenes)

AFFILIATE LINKS

Great resource I use to learn algorithms.
40% off Tech Interview Pro: http://techinterviewpro.com/terriblewhiteboard
20% off CoderPro: http://coderpro.com/terriblewhiteboard


Here is the full implementation.

/**
 * @param {number} n
 * @return {number}
 */
let countPrimes = function(n) {
  let primes = [];
  let primeCount = 0;

  for (let i = 0; i < n; i++) {
    primes.push(true);
  }

  for (let i = 2; i * i < primes.length; i++) {
    if (primes[i]) {
      for (let j = i; j * i < primes.length; j++) {
        primes[i * j] = false;
      }
    }
  }

  for (let i = 2; i < primes.length; i++) {
    if (primes[i]) {
      primeCount++;
    }
  }

  return primeCount;
}