primes

JavaScript, Math, Algorithm

Generates primes up to a given number, using the Sieve of Eratosthenes.

  • Generate an array from 2 to the given number.
  • Use Array.prototype.filter() to filter out the values divisible by any number from 2 to the square root of the provided number.
const primes = num => {
  let arr = Array.from({ length: num - 1 }).map((x, i) => i + 2),
    sqroot = Math.floor(Math.sqrt(num)),
    numsTillSqroot = Array.from({ length: sqroot - 1 }).map((x, i) => i + 2);
  numsTillSqroot.forEach(x => (arr = arr.filter(y => y % x !== 0 || y === x)));
  return arr;
};
Examples
primes(10); // [2, 3, 5, 7]

Recommended snippets

  • primeFactors

    JavaScript, Math

    Finds the prime factors of a given number using the trial division algorithm.

  • luhnCheck

    JavaScript, Math

    Implementation of the Luhn Algorithm used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers etc.

  • arithmeticProgression

    JavaScript, Math

    Creates an array of numbers in the arithmetic progression, starting with the given positive integer and up to the specified limit.