Introduction
In this lab, we will delve into the fascinating world of JavaScript programming. This lab is designed to help you gain practical experience in solving programming problems using JavaScript. You will learn how to generate primes up to a given number using the Sieve of Eratosthenes algorithm.
Generating Primes Using Sieve of Eratosthenes
To generate primes up to a given number using the Sieve of Eratosthenes, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Create an array containing numbers from
2to the given number. - Use
Array.prototype.filter()to filter out the values that are divisible by any number from2to the square root of the provided number. - Return the resulting array containing primes.
Here's the JavaScript code to generate primes up to a given number:
const generatePrimes = (num) => {
let arr = Array.from({ length: num - 1 }).map((x, i) => i + 2),
sqrt = Math.floor(Math.sqrt(num)),
numsTillSqrt = Array.from({ length: sqrt - 1 }).map((x, i) => i + 2);
numsTillSqrt.forEach(
(x) => (arr = arr.filter((y) => y % x !== 0 || y === x))
);
return arr;
};
You can call the function generatePrimes() by passing the desired number as an argument. For example:
generatePrimes(10); // [2, 3, 5, 7]
Summary
Congratulations! You have completed the Primes Up to Given Number lab. You can practice more labs in LabEx to improve your skills.