mildlyAverage
mildlyAverage

Reputation: 13

Process out of memory error using nodejs when nothing should be that large

The exact error says "FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory" The program should get the prime number in the nth position but fails no matter how small the number is. What exactly does this error mean and how do I fix it?

var primes = [2, 3, 5];
var x = 0;
var y = 0;
var z = 6;
var nthPrime = function(number){
    while (primes.length <= number){
        y = 0;
        while (y <= primes.length){
            x = primes[y];
            if (z % x === 0){
                y++;
            } else{
                primes.push(z);
                z++;
            }
        }
    }
    console.log(primes[number]);
};
nthPrime(3);

Upvotes: 1

Views: 181

Answers (1)

Austin Ezell
Austin Ezell

Reputation: 763

The second while loop is an infinite loop. The else statement is happening more frequently than the if statement, after the first two iterations. This means the primes array is increasing in length faster than the y value. Work out the logic some more and this particular error should work itself out.

Upvotes: 1

Related Questions