序列的乘积(阶乘)javascript

product of a sequence (factorial) javascript

想法是在序列中查找数字.. 等式图片:

var pat = document.getElementById("pattern");
var nMax = 96; 

for (var n = 2; n <= 96; n++) {
    if (n != 96)
     pat.innerHTML += 1000 * (999 - 10 * (n - 2))/(1000 - 10 * (n - 2)) + ", ";
    else
        pat.innerHTML += 1000 * (999 - 10 * (n - 2))/(1000 - 10 * (n - 2)) + ",&hellip;";
}
<body>
    <p id="pattern"></p> 
</body>

但问题是 pat.innerHTML 并没有将所有前面的 n 个数字相乘。这个想法是创建一个序列:

a(2) = 1000 * (999 - 10 * (2 - 2))/(1000 - 10 * (2 - 2)) 
a(3) = 1000 * (999 - 10 * (2 - 2))/(1000 - 10 * (2 - 2)) * (999 - 10 * (3 - 2))/(1000 - 10 * (3 - 2))
a(4) = a(3) * (999 - 10 * (4 - 2))/(1000 - 10 * (4 - 2))

等.. 我怎么做? (有关正确数学符号的等式,请参见图片。)

听起来您只需要跟踪保存上次迭代结果的持久变量,并通过乘以它来计算当前迭代的结果。序列从 1000 开始,因此将其作为初始结果:

var pat = document.getElementById("pattern");
let lastResult = 1000;
for (var n = 2; n <= 94; n++) {
  const nextResult = lastResult * ((999 - 10 * (n - 2))/(1000 - 10 * (n - 2)))
  pat.innerHTML += nextResult + '<br>';
  lastResult = nextResult;
}
<body>
    <p id="pattern"></p> 
</body>

最好的方法是制作辅助方法进行计算。 如果您放置另一个 for 循环,那么就像数学需要的那样附加新值。

/*
 Formula
*/

function calcFactoriel(arg) {

 var a = 0; // for numbers
 var b = ""; // for string
 
 for (var x = arg; x > 1; x--) {
 
    if (a == 0) {
      a = 1000 * (999 - 10 * (x - 2))/(1000 - 10 * (x - 2))  
    } else {
      a *= 1000 * (999 - 10 * (x - 2))/(1000 - 10 * (x - 2))  
    }
    
    b = "<div class='m' >" +  a + " , </div> ";
    
 }
 
 return b;
}

var pat = document.getElementById("pattern");
var nMax = 96; 

for (var n = 2; n <= nMax; n++) {
     pat.innerHTML += calcFactoriel(n);
}
.m {
 color: rgba(0,0,0,0.6);
 background: #629552;
 text-shadow: 2px 8px 6px rgba(0,0,0,0.2), 0px -5px 35px rgba(255,255,255,0.3);
}
<body>
    <p id="pattern"></p> 
</body>