I'm trying to make a recursive function to print the factorial of a given integer. Ask the user to enter a positive integer and then display the output on a page. For example, if the user enters 5, the output must be
5 × 4 × 3 × 2 × 1 = 120
var integer = prompt("Enter a positive integer."); function factorialize(num) { if(num == 0 || num == 1) { return 1; } else { return num + " x " + factorialize(num-1) + num * factorialize(num-1); } } document.write(factorialize(integer));
I think make that recursively is quite confused:
function factorialize(n, expression = '', result = 0) { if (n < 0) { return null } else if (n === 0) { return (expression || n) + " = " + result } const newExpression = result? expression + " x " + n: n const newResult =?result: n, result * n return factorialize(n - 1, newExpression. newResult) } console.log(factorialize(5))
Is better to segregate the responsibilities:
function factorial(n) { let fact = 1 if (n < 0) { console.warn("Error"); return 0 } else { for (let i = n; i > 0; i--) { fact = fact * i; } } return fact } function factorialExpression(n) { let expression = "" if (n < 0) { console.warn("Error"); return "" } else { for (let i = n; i > 0; i--) { expression += (i < n? " x ": "") + i } } return expression } function factorialize(n) { if (n === 0 || n === 1) { return n + " = " + n } else if (n > 1) { return factorialExpression(n) + " = " + factorial(n) } return null } console.log(factorialize(5))
You could handover the parts of product and result.
function factorialize(num, product = 1, result = '') { return num === 0 || num === 1? result + (result && ' x ') + num + ' -> ' + product: factorialize(num - 1, product * num, result + (result && ' x ') + num); } console.log(factorialize(5)); console.log(factorialize(2)); console.log(factorialize(1)); console.log(factorialize(0));
You can pass a runningTotal
of the sum so far to each recursive call. You can also keep the solution compact using template literals .
function factorialize(n, runningTotal = 1) { if (n === 1) return `1 = ${runningTotal}`; return `${n} x ${factorialize(n - 1, runningTotal * n)}`; } console.log(factorialize(5));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.