Menu

gitpiper

primes javascript Code Snippet in 2024

mathalgorithmintermediate

Last Updated: 17 December 2024

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; };
primes(10); // [2, 3, 5, 7]

javascript snippet similar to primes For You in December 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️