使用BigInt计算JavaScript中的长阶乘
我们需要编写一个以数字作为唯一输入的JavaScript函数。该函数应计算大数的阶乘(大于10),可以使用JavaScript的新bigInt变量将其阶乘容纳在简单的let或type变量中。最后,该函数应将阶乘转换为字符串并返回该字符串。
例如-如果输入为-
const num = 45;
那么输出应该是-
const output = '119622220865480194561963161495657715064383733760000000000';
示例
为此的代码将是-
const num = 45;
const longFactorial = (num) => {
var bigInt = BigInt(num);
var factorial = 1n;
for (let i = 0n; i < bigInt ; i++) {
factorial *= bigInt − i;
}
return String(factorial);
}
console.log(longFactorial(45));输出结果
控制台中的输出将是-
119622220865480194561963161495657715064383733760000000000