给定n,我们需要找到1 * 1的总和! + 2 * 2! +…….. + n * n!
例子:
Input: 1
Output: 1
Input: 3
Output: 23
1 * 1! + 2 * 2! + 3 * 3! = 1 + 4 + 18 = 23
我们可以假设不会发生溢出。
一个简单的解决方案是逐项计算项并加到结果中。
一个有效的解决方案是基于直接公式(n + 1)! – 1
这个公式如何运作?
We basically need to compute below sum.
∑(i * i!) Where i varies from 1 to n
= ∑((i + 1 – 1) * i!)
= ∑((i+1) * i!) – ∑i!
= ∑(i + 1)! – ∑(i!)
∑(i + 1)! = 2! + 3! + … (n+1)! where 1 <= i <= n —–(1)
∑(i!) = 1! + 2! + 3! + … (n)! where 1 <= i <= n —–(2)
Subtracting second from first, we get (n+1)! – 1
C++
// CPP program to find sum of the series.
#include
using namespace std;
int factorial(int n)
{
int res = 1;
for (int i = 2; i <= n; i++)
res = res * i;
return res;
}
// Function to calculate required series
int calculateSeries(int n)
{
return factorial(n + 1) - 1;
}
// Drivers code
int main()
{
int n = 3;
cout << calculateSeries(n);
return 0;
}
Java
// Java program to find sum of
// the series.
import java.io.*;
class GFG {
static int factorial(int n)
{
int res = 1;
for (int i = 2; i <= n; i++)
res = res * i;
return res;
}
// Function to calculate required
// series
static int calculateSeries(int n)
{
return factorial(n + 1) - 1;
}
// Drivers code
public static void main (String[] args)
{
int n = 3;
System.out.println(
calculateSeries(n));
}
}
// This code is contributed by anuj_67.
Python3
# Python program to find sum of
# the series.
def factorial(n):
res = 1
for i in range(2, n+1):
res = res * i
return res
# Function to calculate required
# series
def calculateSeries(n):
return factorial(n + 1) - 1
# Drivers code
n = 3
print(calculateSeries(n))
# This code is contributed by
# Ansu Kumari.
C#
// C# program to find
// sum of the series.
using System;
class GFG
{
static int factorial(int n)
{
int res = 1;
for (int i = 2; i <= n; i++)
res = res * i;
return res;
}
// Function to calculate
// required series
static int calculateSeries(int n)
{
return factorial(n + 1) - 1;
}
// Driver code
static public void Main ()
{
int n = 3;
Console.WriteLine(
calculateSeries(n));
}
}
// This code is contributed by ajit.
PHP
Javascript
输出:
23