求系列 1+(1+2)/2+(1+2+3)/3+... 之和,直到 N 项
给定一个数字N ,任务是找到以下系列的总和,直到N项。
1+(1+2)/2+(1+2+3)/3+… till N terms
例子:
Input: N = 3
Output: 4.5
Input: N = 4
Output: 7
方法:
从给定的系列中,找到第 N项的公式:
1st term = 1 = 1
2nd term = (1+2)/2 = 1.5
3rd term = (1+2+3)/3 = 2
4th term = (1+2+3+4)/4 = 2.5
.
.
Nth term = N*(N +1)/(2*N) = (N+1)/2
推导:
以下一系列步骤可用于推导公式以找到 N 项的总和 -
The sequence-
1+(1+2)/2+(1+2+3)/3+… till N terms
can be written as-
1 +1.5 +2 +2.5 +3 +3.5 +4 +…till N terms
The above series is an Arithmetic Progression(AP) series. So, we can directly apply the formula of sum of N terms in AP.
The Sum of N terms of an AP can also be given by SN,
SN = N * [First term + Last term] / 2
SN = N * [2 * a + (N – 1) * d] / 2 -(1)
From the above equation, it is known that,
a(first term)=1, d(common difference) = 1.5 -1= 0.5
Substituting the values of a and d in the equation (1), we get-
SN = N * (2 + (N – 1) * 0.5) / 2
插图:
Input: N = 5
Output: 10
Explanation:
SN = 5 * [2 * 1 + (5 – 1) * 0.5] / 2
= 5 * (2 + 2) / 2
= 5 * 2
= 10
下面是实现上述方法的 C++ 程序:
C++
// C++ program to find the sum of the
// series 1+(1+2)/2+(1+2+3)/3+...
// till N terms
#include
using namespace std;
// Function to return the sum
// upto N term of the series
double sumOfSeries(int N)
{
return ((double)N
* (2 + ((double)N - 1) * 0.5))
/ 2;
}
// Driver Code
int main()
{
// Get the value of N
int N = 6;
cout << sumOfSeries(N);
return 0;
}
Java
// Java program to find the sum of the
// series 1+(1+2)/2+(1+2+3)/3+...
// till N terms
import java.util.*;
public class GFG
{
// Function to return the sum
// upto N term of the series
static double sumOfSeries(int N)
{
return ((double)N
* (2 + ((double)N - 1) * 0.5))
/ 2;
}
// Driver Code
public static void main(String args[])
{
// Get the value of N
int N = 6;
System.out.println(sumOfSeries(N));
}
}
// This code is contributed by Samim Hossain Mondal.
Python
# Python program to find the sum of the
# series 1+(1+2)/2+(1+2+3)/3+...
# till N terms
# Function to return the sum
# upto N term of the series
def sumOfSeries(N):
return (N * (2 + (N - 1) * 0.5) / 2)
# Driver Code
# Get the value of N
N = 6
print(sumOfSeries(N))
# This code is contributed by Samim Hossain Mondal.
C#
// C# program to find the sum of the
// series 1+(1+2)/2+(1+2+3)/3+...
// till N terms
using System;
class GFG
{
// Function to return the sum
// upto N term of the series
static double sumOfSeries(int N)
{
return ((double)N
* (2 + ((double)N - 1) * 0.5))
/ 2;
}
// Driver Code
public static void Main()
{
// Get the value of N
int N = 6;
Console.Write(sumOfSeries(N));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
13.5
时间复杂度: O(1)
辅助空间: O(1)