Languages
[Edit]
EN

JavaScript - finding prime numbers with Sieve of Eratosthenes

7 points
Created by:
Selina-Miranda
737

In this short article, we would like to show how to find prime numbers using Sieve of Eratosthenes and JavaScript.

The main idea of the Sieve of Eratosthenes algorithm is to:

  1. generate array of numbers from 2 to N
    (where N is maximal number that we want to check if is prime number),
  2. remove all numbers from the array that are multiplications:
    • of 2 giving 4, 6, 8, 10, ..., N
    • of 3 giving 6, 9, 12, 15, ..., N
    • of 4 giving 8, 12, 16, 20, ..., N
    • ...
    • up to Math.sqrt(N)
  3. the numbers that were not removed are prime numbers.

Main disadvantage of Sieve of Eratosthenes algorithm is necessary to have big amount of operating memory when we want to find really big numbers.

Main advantage of Sieve of Eratosthenes algorithm is simplicity.

 

100 first prime numbers (from 0 up to 100):

Edit
  23 5 7  
 11 13   17 19
   23     29
 31     37  
 41 43   47  
   53     59
 61     67  
 71 73     79
   83     89
       97  

 

Practical example in JavaScript

Edit

In this section removed numbers we mark with false value.

 

Animated prime numbers detection

Edit

In this section we have preseted animation that shows what not prime numbers are removed during next iterations.

 

See also

Edit
  1. JavaScript - sleep function

  2. JavaScript - different approaches to test if number is prime number

References

Edit
  1. Sieve of Eratosthenes - Wikipedia
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join