I've written my own prime number sieve in JavaScript. It loops through numbers 1-100 and puts them in one of two arrays, depending on if it is composite or prime.
I was wondering if there are any inefficient or unnecessary parts of my code that might be slowing down the program. Is there anything I can do so it will work for larger numbers too?
// Creating variables to use later
var cORp;
var primeNums = [];
var compNums = [];
// Create numberSieve function
function numberSieve(x) {
// 0 and 1 are not prime or composite
if (x < 2 && x >= 0) {
cORp = 'neither';
}
// All negative numbers are composite
else if (x < 0) {
cORp = 'composite';
}
// Sieve for positive numbers above 1
else {
// Some more variables for later use
possibleFactors = [];
zFactors = [];
matchingFactors = [];
// Takes all numbers that are half of x and below because they are possible factors
for (i=2; i < x/2+1; i++) {
possibleFactors.push(i);
}
// Takes all possible factors and divides x by them
for (i=0; i < possibleFactors.length; i++) {
z = x/possibleFactors[i];
zFactors.push(z);
}
// Checks if the x divided by the possible factors is equal to any of the other possible factors
for (i in possibleFactors) {
if (zFactors.indexOf(possibleFactors[i]) !== -1) {
matchingFactors.push(possibleFactors[i]);
}
}
// Checks if there are any matching factors
if (matchingFactors.length !== 0) {
cORp = 'composite';
}
else {
cORp = 'prime';
}
}
// Prime numbers go to one array, Composite numbers go to another
if (cORp === 'prime') {
primeNums.push(x);
}
else if (cORp === 'composite') {
compNums.push(x);
}
}
// For each number 0-100 runs the sieve
a=0;
while (a <= 100) {
numberSieve(a);
a++;
}
// Prints out the prime number and composite number arrays
console.log("Prime Numbers: " + primeNums);
console.log("Composite Numbers: " + compNums);
for...in
in javascript, though I can't remember exactly why, other than a lot of complications for non-trivial objects. A regular for loop works just as well \$\endgroup\$ – gengkev Jan 2 '15 at 16:58