You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询:如何实现递归阶乘函数计算过程与结果同步展示?

Solution to Show Factorial Calculation Process

Got it, let's adjust your factorial function to display the full calculation process along with the result! Your original code gets the right answer, but we just need to add a bit of logic to track the multiplication string as we go.

Modified Code

function factorial(n) {
  // Handle edge cases for 0! and 1!
  if (n === 0 || n === 1) {
    alert(`${n}! = 1`);
    return;
  }

  let result = n;
  let calculationStr = `${n}`;

  // Loop from n-1 down to 1 to build the correct multiplication sequence
  for (let i = n - 1; i >= 1; i--) {
    result *= i;
    calculationStr += ` * ${i}`;
  }

  // Show the full process and result
  alert(`${calculationStr} = ${result}`);
}

// Test with input 5
factorial(5); // Alerts "5 * 4 * 3 * 2 * 1 = 120"

Key Changes Explained

  • Edge Case Handling: We added checks for n=0 and n=1 since their factorials are both 1, and we can display a clear message for these cases too.
  • Calculation String Tracking: We initialize calculationStr with the input number, then append each subsequent multiplier (n-1, n-2, ..., 1) to the string during each loop iteration.
  • Loop Adjustment: Instead of counting up from 1, we count down from n-1—this makes it easy to build the multiplication sequence in the intuitive "5 * 4 * 3 * 2 * 1" order, matching what you want to display.

If you prefer to log to the console instead of using an alert, just swap out the alert() calls with console.log()—the core logic stays identical.

内容的提问来源于stack exchange,提问作者Bumblejr2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:14:47