给定一个序列,任务是找到以下序列之和,最多n个项:
1, 8, 27, 64, …
例子:
Input: N = 2
Output: 9
9 = (2*(2+1)/2)^2
Input: N = 4
Output: 100
100 = (4*(4+1)/2)^2
方法:我们可以使用以下公式解决此问题:
Sn = 1 + 8 + 27 + 64 + .........up to n terms
Sn = (n*(n+1)/2)^2
下面是上述opf的实现方法:
C++
// C++ program to find the sum of n terms
#include
using namespace std;
// Function to calculate the sum
int calculateSum(int n)
{
// Return total sum
return pow(n * (n + 1) / 2, 2);
}
// Driver code
int main()
{
int n = 4;
cout << calculateSum(n);
return 0;
}
Java
// Java program to find the sum of n terms
import java.io.*;
class GFG {
// Function to calculate the sum
static int calculateSum(int n)
{
// Return total sum
return (int)Math.pow(n * (n + 1) / 2, 2);
}
// Driver code
public static void main (String[] args) {
int n = 4;
System.out.println( calculateSum(n));
}
}
// This code is contributed by inder_verma..
Python3
# Python3 program to find the
# sum of n terms
#Function to calculate the sum
def calculateSum(n):
#return total sum
return (n * (n + 1) / 2)**2
#Driver code
if __name__=='__main__':
n = 4
print(calculateSum(n))
#this code is contributed by Shashank_Sharma
C#
// C# program to find the sum of n terms
using System;
class GFG
{
// Function ot calculate the sum
static int calculateSum(int n)
{
// Return total sum
return (int)Math.Pow(n * (n + 1) / 2, 2);
}
// Driver code
public static void Main ()
{
int n = 4;
Console.WriteLine(calculateSum(n));
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
PHP
Javascript
输出:
100