Sieve Of Eratosthenes Algorithm

The Sieve of Eratosthenes is an ancient Greek algorithm that efficiently computes a list of prime numbers up to a specified integer. It was developed by the Greek mathematician Eratosthenes of Cyrene in the third century BCE. The algorithm works by iteratively marking the multiples of prime numbers as composite (non-prime) in a given range, starting from the smallest prime number, 2. The process continues until all prime numbers within the desired range have been identified. The algorithm begins by creating a list of integers from 2 to the maximum number, N. It starts with the first number (2) and marks it as prime, then proceeds to eliminate all its multiples (excluding itself) within the list, as these are composite numbers. The algorithm then moves on to the next unmarked number (3), marks it as prime, and removes all its multiples as well. This process is repeated for each subsequent unmarked number in the list until the square of the current number is greater than N. At the end of the process, all the unmarked numbers in the list are prime numbers. The Sieve of Eratosthenes is particularly efficient for finding prime numbers within a small range, and its time complexity is O(N log log N), making it one of the fastest algorithms for this purpose.
function sieveOfEratosthenes (n) {
  /*
     * Calculates prime numbers till a number n
     * :param n: Number upto which to calculate primes
     * :return: A boolean list contaning only primes
     */
  const primes = new Array(n + 1)
  primes.fill(true) // set all as true initially
  primes[0] = primes[1] = false // Handling case for 0 and 1
  const sqrtn = Math.ceil(Math.sqrt(n))
  for (let i = 2; i <= sqrtn; i++) {
    if (primes[i]) {
      for (let j = 2 * i; j <= n; j += i) {
        primes[j] = false
      }
    }
  }
  return primes
}

function main () {
  const n = 69 // number till where we wish to find primes
  const primes = sieveOfEratosthenes(n)
  for (let i = 2; i <= n; i++) {
    if (primes[i]) {
      console.log(i)
    }
  }
}

main()

LANGUAGE:

DARK MODE: