如何在阶乘计算时打印动态生成的乘法运算字符串?

How to print the dynamically generated multiplication operation string during factorial calculation?

我想计算一个数的阶乘并将结果显示给用户。

HTML 表单上有文本字段。用户正在输入要计算其阶乘的数字。

我已经为此编写了一个程序,它运行得非常好。

但我还想在阶乘计算时打印动态生成的乘法运算字符串。

例如,如果用户在文本字段中输入 5,那么在 HTML 表单

的单独文本字段中输出应该如下所示

5*4*3*2*1=120

而且不仅仅是 120

以下是我试过的代码:

<!DOCTYPE HTML>
<html>
 <head>
  <title> New Document </title>
  <script type="text/javascript">
 function fact(num)
 {
    if(num==0)
      return 1;
    return num* fact(num-1);
 }
  </script>
 </head>

 <body>
 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1"><br>
  <input type="button" value="Find factiorial" onclick="this.value=fact(parseInt(txt1.value, 10))">
   </form>
 </body>
</html>

如果您改用常规循环,这会更容易:

 function fact(num){
   let calc = "" + num, res = num;
   while(--num > 0){
     res *= num;
     calc += " * " + num;
   }
   return calc + " = " + res;
 }

或者如果你真的想要递归,你可以传递一个元组类型:

function fact(n, res = 1, calc = ""){
  res *= n;
  calc += (calc ? " * ":"") + n;

  if(n <= 1)
    return [res, calc + " = " + res];

  return fact(n - 1, res, calc);
}

这里有一个稍微不同的方法,它使用迭代函数而不是递归函数:

function fact(n) {
    var numbers = Array.from({length:n}).map(function(_,i) {return i+1;}).reverse();
    return numbers.join("*") + "=" + numbers.reduce(function(c,i) {return c*i},1);
}

有很多事情要做,但代码不多,所以这里有一个细分:

  • Array.from({length:n})
    创建一个所需长度的(空)数组
  • .map(function(_,i) {return i+1;})
    对于数组中的每个条目,使用它的位置加一得到一个数组,如 [1,2,3,4,5]
  • .reverse()
    不言而喻,结果就像 [5,4,3,2,1]
  • numbers.join("*")
    将数字与每个数字之间的 * 粘在一起,因此 5*4*3*2*1
  • numbers.reduce(function(c,i) {return c*i},1)
    对于数组中的每个条目,乘以 "carry"(从 1 开始)。这是阶乘计算的另一种实现方式。

您可以在函数中获取所有中间结果,最后 return 格式化结果。

此函数通过 tail 优化递归工作。

function fact(num, parts = '', result = 1) {
    if (num === 0) {
        return (parts || '0!') + ' = ' + result;
    }
    return fact(num - 1, parts + (parts && ' * ') + num, num * result);
}
<form name="f1">
  Enter the Number: <input type="text" length="8" name="txt1"><br>
  <input type="button" value="Find factiorial" onclick="this.value = fact(+txt1.value)">
</form>

试试这个:

<!DOCTYPE HTML>
<html>
 <head>
  <title> New Document </title>
  <script type="text/javascript">
function fact(num){

  var result = 1,
   str = ""+num+"";
    
    if( num === 0 ){
     return 1;
    }else{
      for(var i = num; i > 0; i--){
        result = result * i;
        if(i > 1){
          str += "*"+(i-1);  
        }
      }
    }
   answer.innerHTML = str + " = " + result;
}

 fact(3);
  </script>
 </head>

 <body>
 <form name="f1">
  Enter the Number  :<input type="number" length="8" name="txt1"><br>
  <input type="button" value="Find factiorial" onclick="fact(parseInt(txt1.value, 10))">
  
   </form>
<div id='answer'></div>
</body>
</html>