简体   繁体   English

序列的乘积(阶乘)javascript

[英]product of a sequence (factorial) javascript

The idea is to find numbers in a sequence.. equation pic:这个想法是在序列中找到数字..等式图片:

方程图像

 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>

But the problem is pat.innerHTML doesn't multiply all previous n numbers.但问题是 pat.innerHTML 不会乘以所有前 n 个数字。 The idea is to create a sequence:这个想法是创建一个序列:

 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))

etc.. How do I do that?等等。我该怎么做? (See pic for the equation in proper math notation.) (有关正确数学符号的方程式,请参见图片。)

It sounds like you just need to keep track of a persistent variable that holds the result from the last iteration, and calculate the result for the current iteration by multiplying by it.听起来您只需要跟踪一个保存上次迭代结果的持久变量,并通过乘以它来计算当前迭代的结果。 The sequence starts at 1000, so put that as the initial result:序列从 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>

Best way is to make helper method for calculation.最好的方法是制作辅助方法进行计算。 If you put another for loop then append new values just like math need's.如果您放置另一个 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM