Primes Up to Given Number

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28556{{"`Primes Up to Given Number`"}} javascript/data_types -.-> lab-28556{{"`Primes Up to Given Number`"}} javascript/arith_ops -.-> lab-28556{{"`Primes Up to Given Number`"}} javascript/comp_ops -.-> lab-28556{{"`Primes Up to Given Number`"}} javascript/higher_funcs -.-> lab-28556{{"`Primes Up to Given Number`"}} end

Generating Primes Using Sieve of Eratosthenes

To generate primes up to a given number using the Sieve of Eratosthenes, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Create an array containing numbers from 2 to the given number.
  3. Use Array.prototype.filter() to filter out the values that are divisible by any number from 2 to the square root of the provided number.
  4. 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.

Other JavaScript Tutorials you may like