Skip to content

Instantly share code, notes, and snippets.

@omas
Last active November 4, 2015 12:05
Show Gist options
  • Save omas/be116fa327ac2e42ff3e to your computer and use it in GitHub Desktop.
Save omas/be116fa327ac2e42ff3e to your computer and use it in GitHub Desktop.
エラトステネスの篩
'use strict';
function getPrimeNumberList(MAX) {
var primeTable = [2];
var workTable = (function(max) {
var result = [];
for (var i = 2; i < max; i++) {
result.push(odd(i));
}
return result;
function odd(n) {
return 2 * n - 1;
}
})(MAX / 2 - 1);
for (var i = 0, len = Math.sqrt(MAX); i < len; i++) {
primeTable.push(workTable[0]);
workTable = sieve(workTable);
}
return (primeTable.concat(workTable));
function sieve(table) {
var divisor = table.shift();
return table.filter(function(v) {
return isIndivisible(v, divisor);
});
function isIndivisible(num, divisor) {
return (num % divisor) !== 0;
}
}
}
console.log(getPrimeNumberList(120));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment