Search code examples
javascriptarraysnested-loopsnanfactorial

Array Factorial. Getting NaN Output. Javascript


var array = [5,4,3,2,1];

document.write("<br>Facorial: " + factorial(array));

//factorial function Ex. 5! = 5*4*3*2*1 = 120

function factorial(params){
        var f = 1;
        for (i = 0; i <= params.length; ++i){
            for (j = 1; j <= params[i]; j++){
                f = f * params[j];
            }
        }
        return f;
    }

I'm trying to make a program where the user inputs a bunch of random numbers in an array and the program calculates different things about those numbers.

I'm trying to have each individual number within my array be factorialed and then presented in the same form.

How I have it right now I'm getting NaN for my output.

What am I doing wrong? Or am I maybe not doing enough?

CURRENT OUTPUT

Factorial: NaN

WHAT I WANT

Factorial: 120,24,6,2,1

Solution

  • Wrong (or at least: odd) things in your code:

    • f is a number. You seem to expect your function to return an array, though?
    • i <= params.length should be i < params.length. Array indices start at 0, and end at length-1.
    • You are multiplying your accumulator variable with params[j] - where j is any number smaller than the currently looked-at array item. This is the reason why you get NaN - when i == 0, it loops until j == 5, and params[5] is undefined - resulting in a NaN result.

    What you want seems to be

    function factorial(n) {
        // function that computes the number n!
        var acc = 1;
        while (n > 0) acc *= n--;
        return acc;
    }
    function facArray(params) {
        var f = [];
        for (var i=0; i<params.length; i++)
            f[i] = factorial(params[i]);
        return f;
    }