Skip to content

Instantly share code, notes, and snippets.

@BenGoldberg1
Created November 30, 2015 04:05
Show Gist options
  • Save BenGoldberg1/ce350a575ddb09b8d50f to your computer and use it in GitHub Desktop.
Save BenGoldberg1/ce350a575ddb09b8d50f to your computer and use it in GitHub Desktop.
<script>
(function (factors, primes) {
var a_prime = 3, a_squared_prime = 9, maybe_prime = 3;
function insertPrimeIntoSieve( factor ) {
/* This functions deliberately makes factors a sparse array */
/* It will have nulls in the places which might be prime, */
/* and primes in the places which are surely composites. */
var where = factor;
while( factors[where] )
where += factor;
/* If sparse arrays hurt your brain, you can pretend I had: */
/* while( factors.length < where ) factors.push(0); */
factors[ where ] = factor;
}
document.write("2 3 ");
while( maybe_prime <= 999 ) {
(function (factor) {
maybe_prime += 2;
if( factor ) {
if( 0 != (maybe_prime % factor) )
throw "Unexpected remainder.";
insertPrimeIntoSieve( factor );
} else if( maybe_prime < a_squared_prime ) {
document.write( maybe_prime + " " );
primes.push( maybe_prime );
} else if( maybe_prime == a_squared_prime ) {
insertPrimeIntoSieve( a_prime );
a_prime = primes.shift();
a_squared_prime = a_prime * a_prime;
} else {
throw "Critical math failure: Programmer or compiler is innumerate.";
}
factors.shift();
})(factors[0]);
}
document.writeln();
})([], []);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment