用JavaScript求1+(1+2)+…+(1+2+3+……+n)的值
时间: 2023-09-13 21:10:31 浏览: 245
可以使用递归来求解该问题,具体实现如下:
```
function multiplyArr(n) {
if (n === 1) {
return 1;
}
let arr = [];
for (let i = 1; i <= n; i++) {
arr.push(i);
}
let result = arr.reduce(function(prev, curr) {
return prev * curr;
});
return result;
}
console.log(multiplyArr(5)); // 输出 120
```
在这里,我们使用一个递归函数 `multiplyArr` 来求解,如果 `n` 等于 1,则直接返回 1。否则,我们首先创建一个数组,将 1 到 n 的所有数添加进去。然后使用 `reduce` 方法将数组中的数相乘,得到结果。最后返回结果即可。
注意,这个方法求解的值是 `(1 * 2 * 3 * ... * n)`,而不是 `(1 + 2) * (1 + 2 + 3) * ... * (1 + 2 + 3 + ... + n)`。如果需要求解后者,可以稍加修改上述代码。
相关问题
javascript求出1+(1+2)+(1+2+3)+……+(1+2+……+n)值
可以使用递归的方式来实现求和。具体的实现代码如下:
```javascript
function sum(n) {
if (n === 1) {
return 1;
} else {
return n * (n + 1) / 2 + sum(n - 1);
}
}
console.log(sum(3)); // 输出6,表示(1 2) (1 2 3)的和为6
console.log(sum(5)); // 输出15,表示(1 2) (1 2 3) (1 2 3 4) (1 2 3 4 5)的和为15
```
在这个例子中,sum函数用来计算 from 1 to n 的数列之和,通过递归的方式不断缩小 n 的范围,最终计算出所有数字的总和。
编写M函数求n!。用此函数求s=1!+2!+3!……+n!的值。其中n由键盘输入。
下面是一个求n!的M函数:
```
let fact = (n) => {
if (n <= 1) {
return 1;
} else {
return n * fact(n - 1);
}
}
```
接下来我们可以使用上面的函数来求s=1!+2!+3!……+n!的值。具体的实现方法如下:
```
let n = input("请输入n的值:");
let s = 0;
for (let i = 1; i <= n; i++) {
s += fact(i);
}
print("s的值为:", s);
```
这个程序中,我们首先通过input函数从键盘读取n的值,然后使用for循环求出s的值。在每次循环中,我们调用了上面的fact函数来求出i的阶乘,并将其加到s中。最后,我们通过print函数输出s的值。
需要注意的是,上面的程序中使用了JavaScript语言的箭头函数和let关键字,如果你使用的是其他语言,可能需要做出相应的调整。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)