Search code examples
javascripthtmlfactorization

How could i write out each individual number as well as the asterisk symbol when calculating the factorial of a number?


I'm stuck on a problem that requires me to display the full workings of a factorial function, for example, if the user wanted to workout 6!, i would need to display: 6 * 5 * 4 * 3 * 2 * 1 = 720. Would i need to use an array for such?

This is what i have so far in order to workout the factorized value of any user given number, although this only outputs the final value, and not the fully expanded working out as i have shown above:

(the variable number contains the user input);

var f = [];
function factorizeFunction(number) { //this is the function that does the factorization calculations
  if (number == 0 || number == 1)
    return 1;
  if (f[number] > 0)
    return f[number];
  return f[number] = factorizeFunction(number-1) * number;
}
document.getElementById("factorialTest").innerHTML = factorizeFunction(number);

any help on this would be appreciated!


Solution

  • One option is, on each iteration, push to an array which is passed down through the recursive call (or created on the initial call). At the end, return the array, joined by *, and also the sum of the array:

    function factorizeFunction(number, arr = []) { //this is the function that does the factorization calculations
      if (number == 0 || number == 1) arr.push(number);
      else {
        arr.push(number);
        factorizeFunction(number - 1, arr);
      }
      return arr.join(' * ') + ' = ' + arr.reduce((a, b) => a * b, 1);
    }
    document.getElementById("factorialTest").innerHTML = factorizeFunction(5);
    <div id="factorialTest"></div>