求阶乘之和,直到 N 阶乘 (1! + 2! + 3! + ... + N!)
给定一个正整数N 。任务是从 1 计算阶乘之和!到 N!, 1! + 2! + 3! + ... + N! .
例子:
Input: N = 5
Output: 153
Explanation: 1! + 2! + 3! + 4! + 5! = 1 + 2 + 6 + 24 + 120 = 153.
Input: N = 1
Output: 1
朴素方法:解决这个问题的基本方法是找到所有数字的阶乘,直到 1 到 N 并计算它们的总和。
时间复杂度:O(N^2)
辅助空间:O(1)
方法:一种有效的方法是在同一循环中计算阶乘和求和,使时间为 O(N)。遍历从 1 到 N 的数字,对于每个数字 i:
- 将 i 与先前的阶乘(最初为 1)相乘。
- 将此新阶乘添加到集体总和中
最后,打印这个集体总和。
下面是上述方法的实现。
C++
// C++ program to compute sum of series
// 1! + 2! + 3! + ... + N!
#include
using namespace std;
// Function to return sum
// of 1!, 2! upto N!
int findFactSum(int N)
{
// Initializing the variables
int f = 1, Sum = 0;
// Calculate the factorial and sum
// in the same loop
for (int i = 1; i <= N; i++) {
f = f * i;
Sum += f;
}
// Return Sum as the final result.
return Sum;
}
// Driver Code
int main()
{
int N = 5;
// Function call
cout << findFactSum(N);
return 0;
}
Java
// Java code to implement above approach
class GFG {
// Function to return sum
// of 1!, 2! upto N!
static int findFactSum(int N)
{
// Initializing the variables
int f = 1, Sum = 0;
// Calculate the factorial and sum
// in the same loop
for (int i = 1; i <= N; i++) {
f = f * i;
Sum += f;
}
// Return Sum as the final result.
return Sum;
}
// Driver code
public static void main(String[] args)
{
int N = 5;
System.out.print(findFactSum(N));
}
}
// This code is contributed ukasp.
Python3
# python program to compute sum of series
# 1! + 2! + 3! + ... + N!
# Function to return sum
# of 1!, 2! upto N!
def findFactSum(N):
# Initializing the variables
f = 1
Sum = 0
# Calculate the factorial and sum
# in the same loop
for i in range(1, N + 1):
f = f * i
Sum += f
# Return Sum as the final result.
return Sum
# Driver Code
if __name__ == "__main__":
N = 5
# Function call
print(findFactSum(N))
# This code is contributed by rakeshsahni
C#
// C# code to implement above approach
using System;
class GFG
{
// Function to return sum
// of 1!, 2! upto N!
static int findFactSum(int N)
{
// Initializing the variables
int f = 1, Sum = 0;
// Calculate the factorial and sum
// in the same loop
for (int i = 1; i <= N; i++) {
f = f * i;
Sum += f;
}
// Return Sum as the final result.
return Sum;
}
// Driver code
public static void Main()
{
int N = 5;
Console.Write(findFactSum(N));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出:
153
时间复杂度:O(N)
辅助空间:O(1)