I've been playing around with the code challenges on projecteuler.net. A few of them involve prime numbers, so I've created a function to find them based on the sieve of Eratosthenes.
It works fine, and is reasonably quick for small numbers, but much slower for the challenges that involve the larger numbers, like 2million. So to try to improve my function I tested it to see how the performance changes and discovered that the time it takes to run shoots up dramatically at a specific number, not gradually as you might expect.
I'm running this on the chrome dev tools. It consistently takes about 1.5 seconds for 354,957 and 15 seconds for 354,958. I found this very odd and was wondering if anyone had experienced similar or new why this might be?
Below is my code. I know it's not perfect and there a much (much) quicker implementations out there.
function getPrimesUnder(number) {
var start = new Date().getTime();
var numbers = [2];
var sqNum = Math.sqrt(number);
var i, x;
for (i = 3; i < number; i = i + 2) {
numbers.push(i);
}
for (x = 0; numbers[x] < sqNum; x++) {
for (i = 0; i < numbers.length ; i++){
if (numbers[i] > numbers[x]) {
if(numbers[i] % numbers[x] === 0){
numbers.splice(i, 1)
}
}
}
}
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time/1000 + ' seconds');
return numbers;
}