gpt4 book ai didi

javascript - 通过创建数组并将其相乘来对数字进行因式分解

转载 作者:行者123 更新时间:2023-11-30 08:27:54 25 4
gpt4 key购买 nike

我正在经历 FreeCodeCamp 挑战之一。

" Return the factorial of the provided integer.

If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n.

Factorials are often represented with the shorthand notation n!

For example: 5! = 1 * 2 * 3 * 4 * 5 = 120 "

我已经知道最简单的方法是使用递归,但当我发现这个事实时,我已经在尝试通过创建一个数组、将数字压入其中并将它们相乘来解决问题。但是我卡在了这一步。我根据函数 factorialize 参数创建了一个包含位数的数组,但我无法获得这些位数的乘积。我做错了什么:

function factorialize(num) {
var array = [];
var product;
for(i = 0; i<=num;i++) {
array.push(i);
for (j=0; j < array.length; j++) {
product *= array[j];
}
return product;
}
}
factorialize(5);

最佳答案

我认为最简单的方法是创建一个范围并缩小范围:

var n = 5;

function factorize(max) {
return [...Array(max).keys()].reduce((a,b) => a * (b + 1), 1);
}

console.log(factorize(n));

关于javascript - 通过创建数组并将其相乘来对数字进行因式分解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42346709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com