📌  相关文章
📜  程序打印-1 + 2 + 11 + 26 + 47 +…系列的总和。

📅  最后修改于: 2021-05-06 20:39:30             🧑  作者: Mango

给定数字N,任务是找到序列的前N个数字之和:

例子:

Input: N = 3
Output: 12
Explanation:
Sum = (N * (N + 1) * (2 * N - 5) + 4 * N) / 2
    = (3 * (3 + 1) * (2 * 3 - 5) + 4 * 3) / 2
    = 12

Input: N = 9
Output: 603

方法:
给定级数的N个项可以概括为:
系列的第N个词T_n =3 * n * n - 6 * n + 2
$S_n=3\sum_{i=1}^n N^2 - 6\sum_{i=1}^n N+ 2 \sum_{i=1}^n 1\\\\ S_n=3*\frac{n(n+1)(2n+1)}{6}-6*\frac{n(n+1)}{2} +2n\\\\ S_n=\frac{n(n+1)(2n-5)+4n}{2} $
下面是上述方法的实现:

C++
// CPP program to find SUM
// upto N-th term of the series:
// -1, 2, 11, 26, 47, 74, .....
 
#include 
using namespace std;
 
// calculate Nth term of series
int findSum(int N)
{
    return (N * (N + 1) * (2 * N - 5) + 4 * N) / 2;
}
 
// Driver Function
int main()
{
 
    // Get the value of N
    int N = 3;
 
    // Get the sum of the series
    cout << findSum(N) << endl;
 
    return 0;
}


Java
// Java program to find SUM
// upto N-th term of the series:
// -1, 2, 11, 26, 47, 74, .....
import java.util.*;
 
class solution
{
 static int findSum(int N)
{
 return (N * (N + 1) * (2 * N - 5) + 4 * N) / 2;
}
 
//driver function
public static void main(String arr[])
{
  // Get the value of N
    int N = 3;
 
 // Get the sum of the series
   System.out.println(findSum(N));
 
}
}
//THis code is contributed by
//Surendra_Gangwar


Python3
# Python3 program to find sum
# upto N-th term of the series:
# -1, 2, 11, 26, 47, 74, .....
 
# calculate Nth term of series
def findSum(N):
     
    return ((N * (N + 1) *
           (2 * N - 5) + 4 * N) / 2)
     
#Driver Function
if __name__=='__main__':
     
    #Get the value of N
    N = 3
 
    #Get the sum of the series
    print(findSum(N))
 
#this code is contributed by Shashank_Sharma


C#
// C# program to find SUM
// upto N-th term of the series:
// -1, 2, 11, 26, 47, 74, .....
using System;
 
class GFG
{
static int findSum(int N)
{
    return (N * (N + 1) *
           (2 * N - 5) + 4 * N) / 2;
}
 
// Driver Code
static public void Main ()
{
    // Get the value of N
    int N = 3;
     
    // Get the sum of the series
    Console.Write(findSum(N));
}
}
 
// This code is contributed by Raj


PHP


Javascript


输出:
12

时间复杂度: O(1)