JSFiddle - React, Tailwind, and code Playground
HTML
<div id="out"></div>
JavaScript
function* prime() {
var cur = 3; /** start with 3 **/
yield 2; /** 2 is a prime **/
let foundPrimes = [2]; /** store in array of found primes **/
while(1) {
let isPrime = true;
/** loop through found primes **/
for (var i = 0; i < foundPrimes.length; i++) {
let p = foundPrimes[i];
/** if the current value is divisible by one
of the found primes it is not prime itself **/
if (cur % p === 0) {
isPrime = false;
break;
}
/** we need not go further than cur/2 **/
if (p > cur/2) {
break;
}
}
/** if a prime was found yield it
and add it to the array of found primes **/
if (isPrime) {
yield cur;
foundPrimes.push(cur);
}
++cur;
}
}
let out = document.getElementById("out");
let outStr = "";
let it = prime();
for (var i = 0; i < 20; i++) {
let cur = it.next();
console.log(cur.value);
outStr += `${cur.value} <br>`;
}
out.innerHTML = outStr;