Millionth Prime - chunked code
Computes the millionth prime using closures and chunked code.
by Ray Toal
HTML
<div>
<p>The millionth prime is
<span id="answer"><button id="go">Find it</button></span>
</p>
<p>While computing, try typing into this box:</p>
<textarea rows="10" cols="50"></textarea>
</div>
JavaScript
document.getElementById("go").onclick = function() {
var n = 2,
count = 0;
var findMore = function() {
Find: for (; true; n += 1) {
for (var k = 2, last = Math.sqrt(n); k <= last; k += 1) {
if (n % k === 0) {
continue Find;
}
}
count += 1;
if (count === 1000000) {
document.getElementById("answer").innerHTML = n;
return;
} else if (count % 10000 === 0) {
document.getElementById("answer").innerHTML = "(found " + count + " so far)";
setTimeout(findMore, 50);
n += 1;
return;
}
}
};
findMore();
};