📌  相关文章
📜  程序找出23+ 45+ 75 + …….最多N个数列的和

📅  最后修改于: 2021-05-06 22:06:28             🧑  作者: Mango

给定数字N,任务是找到以下系列的第N个项:

例子:

Input: N = 4
Output: 256
Explanation:
Nth term = (2 * N * (N + 1) * (4 * N + 17) + 54 * N) / 6
         = (2 * 4 * (4 + 1) * (4 * 4 + 17) + 54 * 4) / 6
         = 256

Input: N = 10
Output: 2180

方法:
给定级数的N个项可以概括为:
T_n = ( 2 * n + 3 )^2 - 2 * n\\ T_n = 4 * n^2+ 10*n+9
该系列的前n个项的总和:
$S_n=4\sum_{i=1}^n n^2+10\sum_{i=1}^n n +9\sum_{i=1}^n 1\\\\ S_n=4\frac{n(n+1)(2n+1)}{6}+30\frac{n(n+1)}{2} +9n\\\\ $
因此,该系列的前n个项之和:

*** QuickLaTeX cannot compile formula:
 

*** Error message:
Error: Nothing to show, formula is empty

下面是上述方法的实现:

C++
// CPP program to find sum
// upto N-th term of the series:
// 23, 45, 75, 113...
 
#include 
using namespace std;
 
// calculate Nth term of series
int findSum(int N)
{
    return (2 * N * (N + 1) * (4 * N + 17) + 54 * N) / 6;
}
 
// Driver Function
int main()
{
 
    // Get the value of N
    int N = 4;
 
    // 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:
// 23, 45, 75, 113...
import java.util.*;
 
class solution
{
     
static int findSum(int N)
{
    //return the final sum
    return (2 * N * (N + 1) * (4 * N + 17) + 54 * N) / 6;
}
 
//Driver program
public static void main(String arr[])
{
// Get the value of N
    int N = 4;
 
// Get the sum of the series
 System.out.println(findSum(N));
 
}
}


Python3
# Python3 program to find sum
# upto N-th term of the series:
# 23, 45, 75, 113...
 
# calculate Nth term of series
def findSum(N):
     
    return (2 * N * (N + 1) * (4 * N + 17) + 54 * N) / 6
     
#Driver Function
if __name__=='__main__':
#Get the value of N
    N = 4
 
#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:
// 23, 45, 75, 113...
using System;
 
class GFG
{
     
static int findSum(int N)
{
    //return the final sum
    return (2 * N * (N + 1) *
           (4 * N + 17) + 54 * N) / 6;
}
 
// Driver Code
static void Main()
{
    // Get the value of N
    int N = 4;
     
    // Get the sum of the series
    Console.Write(findSum(N));
}
}
 
// This code is contributed by Raj


PHP


Javascript


输出:
256

时间复杂度: O(1)