6.4 求 ,(即求1!+2!+3!+4!+5!+…+n!) 输入格式: 5 输出格式: 153
时间: 2023-10-08 21:05:35 浏览: 168
算法1:循环迭代
1. 初始化result为1
2. for循环从1到n,每次将i的阶乘乘到result中
3. 返回result
时间复杂度:O(n)
C++ 代码
class Solution {
public:
int getFactorialSum(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
int factorial = 1;
for (int j = 1; j <= i; j++) {
factorial *= j;
}
result += factorial;
}
return result;
}
};
Python 代码
class Solution:
def getFactorialSum(self, n: int) -> int:
result = 1
for i in range(1, n + 1):
factorial = 1
for j in range(1, i + 1):
factorial *= j
result += factorial
return result
时间复杂度:O(n^2)
算法2:递归
1. 递归终止条件为n=1,返回1
2. 递归调用getFactorialSum(n-1),并将返回值加上n的阶乘
时间复杂度:O(n^2)
C++ 代码
class Solution {
public:
int getFactorialSum(int n) {
if (n == 1) {
return 1;
}
return getFactorialSum(n - 1) + getFactorial(n);
}
int getFactorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
};
Python 代码
class Solution:
def getFactorialSum(self, n: int) -> int:
if n == 1:
return 1
return self.getFactorialSum(n - 1) + self.getFactorial(n)
def getFactorial(self, n: int) -> int:
result = 1
for i in range(1, n + 1):
result *= i
return result
阅读全文