0
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
GreenFerret95
  • 117
  • 1
  • 12

4 Answers4

1

You could make use of this fact function taken from Felix Kling's answer here and use Array.map and then Array.join

function fact(x) {
   if(x == 0) return 1;
   return x * fact(x-1);
}
function factorial(arr){
   var result = arr.map(fact);
   return result.join(",");
}
Community
  • 1
  • 1
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
1

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;
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

try this code

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

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

function factorial(params){
        var op = [];
        for (i = params.length - 1; i >= 0 ; i--){
            var f = 1;
            for (j = 0; j < i; j++){
                f = f * params[j];
            }
             op.push(f);
        }
       return op;
    }
Girish
  • 11,907
  • 3
  • 34
  • 51
0

That's all in a while :D

var array = [5,4,3,2,1];
var len = array.length-1;
while(len--) {
    array[len] *= array[len+1];
}

array;// [120, 24, 6, 2, 1]

Just multiply one by one from last to first.

Leo
  • 13,428
  • 5
  • 43
  • 61