给定数字N,任务是找到以下系列的前N个项的总和:
Sn = 2 + 10 + 30 + 68 + … upto n terms
例子:
Input: N = 2
Output: 12
2 + 10
= 12
Input: N = 4
Output: 40
2 + 10 + 30 + 68
= 110
方法:让第n个项用tn表示。
可以通过如下拆分每个术语来轻松解决此问题:
Sn = 2 + 10 + 30 + 68 + ......
Sn = (1+1^3) + (2+2^3) + (3+3^3) + (4+4^3) +......
Sn = (1 + 2 + 3 + 4 + ...unto n terms) + (1^3 + 2^3 + 3^3 + 4^3 + ...upto n terms)
我们观察到Sn可以分解为两个系列的总和。
因此,前n个项的总和如下:
Sn = (1 + 2 + 3 + 4 + ...unto n terms) + (1^3 + 2^3 + 3^3 + 4^3 + ...upto n terms)
Sn = n*(n + 1)/2 + (n*(n + 1)/2)^2
下面是上述方法的实现:
C++
// C++ program to find sum of first n terms
#include
using namespace std;
// Function to calculate the sum
int calculateSum(int n)
{
return n * (n + 1) / 2
+ pow((n * (n + 1) / 2), 2);
}
// Driver code
int main()
{
// number of terms to be
// included in the sum
int n = 3;
// find the Sum
cout << "Sum = " << calculateSum(n);
return 0;
}
Java
// Java program to find sum of first n terms
public class GFG {
// Function to calculate the sum
static int calculateSum(int n)
{
return n * (n + 1) / 2
+ (int)Math.pow((n * (n + 1) / 2), 2);
}
// Driver code
public static void main(String args[])
{
// number of terms to be
// included in the sum
int n = 3;
// find the Sum
System.out.println("Sum = "+ calculateSum(n));
}
// This Code is contributed by ANKITRAI1
}
Python3
# Python program to find sum
# of first n terms
# Function to calculate the sum
def calculateSum(n):
return (n * (n + 1) // 2 +
pow((n * (n + 1) // 2), 2))
# Driver code
# number of terms to be
# included in the sum
n = 3
# find the Sum
print("Sum = ", calculateSum(n))
# This code is contributed by
# Sanjit_Prasad
C#
// C# program to find sum of first n terms
using System;
class gfg
{
// Function to calculate the sum
public void calculateSum(int n)
{
double r = (n * (n + 1) / 2 +
Math.Pow((n * (n + 1) / 2), 2));
Console.WriteLine("Sum = " + r);
}
// Driver code
public static int Main()
{
gfg g = new gfg();
// number of terms to be
// included in the sum
int n = 3;
// find the Sum
g.calculateSum(n);
Console.Read();
return 0;
}
}
PHP
Javascript
输出:
Sum = 42