blackpanther
blackpanther

Reputation: 11486

JavaScript recursive function not returning the right output

I have the following recursive function that checks to see whether the output array has a length of 100. If it has a length less than a 100, the function is recursively called and the argument variable n is incremented by 1 as follows:

var eratosthenes = function(n) {
    // Eratosthenes algorithm to find all primes under n
    var array = new Array(), upperLimit = Math.sqrt(n), output = new Array();

    // Make an array from 2 to (n - 1)
    for (var i = 0; i < n; i++) {
        array.push(true);
    }

    // Remove multiples of primes starting from 2, 3, 5,...
    for (var i = 2; i <= upperLimit; i++) {
        if (array[i]) {
            for (var j = i * i; j < n; j += i) {
                array[j] = false;
            }
        }
    }

    // All array[i] set to true are primes
    for (var i = 2; i < n; i++) {
        if(array[i]) {
            output.push(i);
        }
    }
    if (output.length < 100){
        eratosthenes(n+1);
    } else {
        return output;
    }
};

Once the array, of correct length, has been calculated, I then format the output array using the following function:

var fmt = function(arr){
    return arr.join();
}

But, when I call the eratosthenes function as follows: eratosthenes(100) the returned array causes an exception in the fmt function. But, if the eratosthenes function is called as follows: eratosthenes(545) where the output array has a length = 100, the array can be passed to the fmt function without a problem. Is there any way to resolve this problem with recursion?

Upvotes: 0

Views: 104

Answers (1)

Blender
Blender

Reputation: 298106

You need to return the result of your function call:

return eratosthenes(n+1);

Upvotes: 5

Related Questions