求系列 1^2, (1^2+2^2), (1^2+2^2+3^2), .... 的 N 项之和
给定一个正整数N 。找到系列的前N 项的总和-
12, (12+22), (12+22+32),….,till N terms
例子:
Input: N = 3
Output: 20
Input: N = 1
Output: 1
方法:使用以下模式形成序列。对于任何值 N-
SN = N * (N+1)2 * (N+2) / 12
下面是上述方法的实现:
C++
// C++ program to implement
// the above approach
#include
using namespace std;
// Function to return sum of
// N term of the series
int findSum(int N){
return N*(N+1)*(N+1)*(N+2)/12;
}
// Driver Code
int main()
{
int N = 3;
cout << findSum(N);
}
Java
// Java program to implement
// the above approach
class GFG {
// Function to return sum of
// N term of the series
static int findSum(int N) {
return N * (N + 1) * (N + 1) * (N + 2) / 12;
}
// Driver Code
public static void main(String args[]) {
int N = 3;
System.out.print(findSum(N));
}
}
// This code is contributed by Saurabh Jaiswal
Python3
# Python 3 program for the above approach
# Function to return sum of
# N term of the series
def findSum(N):
return N*(N+1)*(N+1)*(N+2)//12
# Driver Code
if __name__ == "__main__":
# Value of N
N = 3
print(findSum(N))
# This code is contributed by Abhishek Thakur.
C#
// C# program to implement
// the above approach
using System;
class GFG
{
// Function to return sum of
// N term of the series
static int findSum(int N){
return N*(N+1)*(N+1)*(N+2)/12;
}
// Driver Code
public static void Main()
{
int N = 3;
Console.Write(findSum(N));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
20
时间复杂度:O(1)
辅助空间:O(1)