Sieve redux
HTML
<html>
<head>
</head>
<body>
<strong>Please enter a number greater than "2" to begin our journey through the Sieve of Eratosthenes</strong>
<br><br>
<input type = textbox id = input value = 2>
<br>
<br>
<input type = button id = enqueue onclick = enq() value = "Enqueue">
<br>
<input type = button id = enqueue onclick = prn() value = "Print">
<input type = button id = enqueue onclick = deq() value = "Dq">
<div id = "out">
</div>
<input type = button id = sieve onclick = 'SoE()' value = "Sieve">
</body>
</html>
JavaScript
var q1 = new Queue();
var q2 = new Queue();
function Queue() {
this.head = null;
this.tail = null;
this.length = 0;
}
function Node() {
this.content = null;
this.next = null;
}
Queue.prototype.nq = function(data) {
var node = new Node();
node.content = data;
if (this.head == null) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
this.tail = node;
}
this.length++;
return this;
}
Queue.prototype.dq = function() {
var val = this.head.content;
if (this.head != null) {
this.head = this.head.next;
this.length--;
}
return val;
}
Queue.prototype.print = function() {
var traveler = this.head;
var s = '';
while (traveler){
s += traveler.content + ', ';
traveler= traveler.next;
}
return s;
}
Queue.prototype.clear = function() {
this.head = null;
this.tail = null;
this.length = 0;
}
function SoE() {
while (q1.head != null) {
if (checkIfPrime(q1.head.content)) {
q2.nq(q1.dq());
} else {
q1.dq();
}
}
document.getElementById('out').innerHTML = q2.print();
}
function checkIfPrime(candidate) {
var max = Math.floor(Math.sqrt(candidate));
var traveler = q2.head;
while (traveler != null && traveler.content <= max) {
if (candidate % traveler.content == 0) {
return false;
}
traveler = traveler.next;
}
return true;
}
function enq() {
var num = document.getElementById("input").value;
q1.clear();
q2.clear();
document.getElementById("out").innerHTML= '';
for (var i = 2; i <= num; i++){
q1.nq(i);
}
}
function prn() {
alert(q1.print() + '<br>' + q2.print());
}
function deq () {
alert(q1.dq());
}