求系列 5, 11, 19, 29, 41, 的前 N 项的总和。 . .
给定一个整数N 。任务是找到序列 5、11、19、29、41 的前N 项的总和。 . .直到第 N 学期。
例子:
Input: N = 5
Output: 105
Explanation: 5 + 11 + 19 + 29 + 41 = 105.
Input: N = 2
Output: 16
Explanation: The terms are 5 and 11
方法:从给定的系列中首先确定第 N 项:
1st term = 5 = 1 + 4 = 1 + 22
2nd term = 11 = 2 + 9 = 2 + 32
3rd term = 19 = 3 + 16 = 3 + 42
4th term = 29 = 4 + 25 = 4 + 52
.
.
Nth term = N + (N+1)2
所以第N项可以写成: T N = N + (N+1) 2
因此, N项的总和变为
1 + 22 + 2 + 32 + 3 + 42 + . . . + N + (N+1)2
= [1 + 2 + 3 + . . . + N] + [22 + 32 + 42 + . . . + (N+1)2]
= (N*(N+1))/2 + [(N+1)*(N+2)*(2*N + 3)]/6 – 1
= [N*(N+2)*(N+4)]/3
因此前N项的总和可以给出为: S N = [N*(N+2)*(N+4)]/3
插图:
For example, take N = 5
The output will be 105.
Use N = 5, then N*(N+2)*(N+4)/3
= 5 * 7 * 9/3 = 5 * 7 * 3 = 105.
This is same as 5 + 11 + 19 + 29 + 41
下面是上述方法的实现。
C++
// C++ code to implement the above approach
#include
using namespace std;
// Function to calculate
// the sum of first N terms
int nthSum(int N)
{
// Formula for sum of N terms
int ans = (N * (N + 2) * (N + 4)) / 3;
return ans;
}
// Driver code
int main()
{
int N = 5;
cout << nthSum(N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
public class GFG
{
// Function to calculate
// the sum of first N terms
static int nthSum(int N)
{
// Formula for sum of N terms
int ans = (N * (N + 2) * (N + 4)) / 3;
return ans;
}
// Driver code
public static void main(String args[])
{
int N = 5;
System.out.println(nthSum(N));
}
}
// This code is contributed by Samim Hossain Mondal.
Python3
# Python code to implement the above approach
# Function to calculate
# the sum of first N terms
def nthSum(N):
# Formula for sum of N terms
ans = (int)((N * (N + 2) * (N + 4)) / 3)
return ans
# Driver code
N = 5
print(nthSum(N))
# This code is contributed by Taranpreet
C#
// C# program for the above approach
using System;
class GFG
{
// Function to calculate
// the sum of first N terms
static int nthSum(int N)
{
// Formula for sum of N terms
int ans = (N * (N + 2) * (N + 4)) / 3;
return ans;
}
// Driver code
public static void Main()
{
int N = 5;
Console.Write(nthSum(N));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
105
时间复杂度: O(1)
辅助空间: O(1)