<h1>
Prime numbers - Sieve of Eratosthenes
</h1>
<h2>
Written in pure JavaScript
</h2>
Prime numbers with max limit of <label for="console" id="consoleLabel">500</label><br />
<textarea name="console" id="console" cols="80" rows="20" readonly tabindex="2"></textarea>
<br />
<input type="number" name="limit" id="limit" value="500" min="2" tabindex="1" onchange="writePrimes(this.value)" />
body {
background-color: linen;
}
#consoleLabel,
#limit {
font-weight: bold;
color: tomato;
}
#console {
font-family: "Lucida Sans", "Lucida Sans Regular", "Lucida Grande",
"Lucida Sans Unicode", Geneva, Verdana, sans-serif;
background-color: black;
color: limegreen;
}
#limit {
height: 40px;
line-height: 2em;
padding: 10px;
}
/* Sieve of Eratosthenes
Author: https://github.com/Amarok24
Version: 0.2
Date: 2020-01-07
License: The Unlicense. For more information, please refer to http://unlicense.org
(A license with no conditions whatsoever which dedicates works to the public domain. Unlicensed works, modifications, and larger works may be distributed under different terms and without source code.)
*/
"use strict";
function getPrimes(maxLimit) {
let field = [];
let primes = [2];
let currentPrime = 2;
let currentIndex = 2;
let stopAfter = Math.floor(Math.sqrt(maxLimit));
// stopAfter = highest index after which no other primes
// will be sieved (simplest code optimization)
if (maxLimit < 2) {
return [-1];
} else if (maxLimit === 2) {
return primes;
}
for (let i=0; i<=maxLimit; i++) {
field.push(i); // field will contain [0, 1, 2, 3, ... maxLimit]
}
while (currentPrime <= stopAfter) {
// with maxLimit of 50 this will run up to currentPrime 7, not beyond
currentIndex += currentPrime;
while (currentIndex <= maxLimit) {
field[currentIndex] = 0; // mark as removed from field
currentIndex += currentPrime;
}
// now let's go to the the very next prime number in field
currentIndex = currentPrime;
while (true) {
currentIndex++;
if (field[currentIndex] !== 0) {
break; // break while loop
}
}
currentPrime = currentIndex;
primes.push(currentPrime);
}
// now let's populate the primes array with all remaining numbers from field
currentIndex++;
for (let i = currentIndex; i <= maxLimit; i++) {
if (field[i] !== 0) {
primes.push(field[i]);
}
}
return primes;
}
function writePrimes(maxLimit) {
let output = document.getElementById("console");
let label = document.getElementById("consoleLabel");
let p = getPrimes(maxLimit);
let outS = "", i = 0;
const lastI = p.length-1;
label.innerText = maxLimit.toString();
output.innerText = "";
while (i<p.length) {
outS += p[i].toString();
if (i !== lastI) outS += ", ";
i++;
}
output.innerText = outS;
}
writePrimes(500);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.