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

Exception or error:

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!

How to solve:

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>

###

Use map and join methods.

const factorString = num => {
    const nums = new Array(num).fill(0).map((_, i) => num - i);
    let res = 1;
    nums.forEach(x => res *= x);
    return `${nums.join(' * ')} = ${res}`;
}

console.log(factorString(6))

###

You could change the return signature of the function and expect an array of an array with the factors and the product.

function factorize(number) {
    if (number === 0 || number === 1) return [[1], 1];
    var [factors, product] = factorize(number - 1);
    return [[...factors, number], product * number];
}

console.log(factorize(5));

Leave a Reply

Your email address will not be published. Required fields are marked *