📌  相关文章
📜  求出系列3、7、13、21、31…的总和。

📅  最后修改于: 2021-04-23 06:31:28             🧑  作者: Mango

给定一个数N的任务是找到以下系列总和高达n项。

例子

Input : N = 3
Output : 23

Input : N = 25
Output : 5875

方法:

    Let $$S=0+3+7+13+21+31+.......+a_{n-1}+a_n$$ $$S=3+7+13+21+31+...+a_{n-2}+a_{n-1}+a_n$$

减去以上两个等式,我们得到:

图像

下面是上述方法的实现:

C++
// C++ Program to find the sum of given series
 
#include 
#include 
 
using namespace std;
 
// Function to calculate sum
int findSum(int n)
{
    // Return sum
    return (n * (pow(n, 2) + 3 * n + 5)) / 3;
}
 
// Driver code
int main()
{
    int n = 25;
 
    cout << findSum(n);
 
    return 0;
}


Java
// Java program to find sum of
// n terms of the given series
import java.util.*;
 
class GFG
{
static int calculateSum(int n)
{
    // returning the final sum
    return (n * ((int)Math.pow(n, 2) + 3 *
                               n + 5)) / 3;
}
 
// Driver Code
public static void main(String arr[])
{
    // number of terms to
    // find the sum
    int n = 25;
    System.out.println(calculateSum(n));
}
}
 
// This code is contributed
// by Surendra_Gangwar


Python 3
# Python program to find the
# sum of given series
 
# Function to calculate sum
def findSum(n):
    # Return sum
    return (n*(pow(n, 2)+3 * n + 5))/3
 
# driver code
n = 25
 
print(int(findSum(n)))


C#
// C# program to find
// sum of n terms of
// the given series
using System;
 
class GFG
{
static int calculateSum(int n)
{
    // returning the final sum
    return (n * ((int)Math.Pow(n, 2) + 3 *
                               n + 5)) / 3;
}
 
// Driver Code
public static void Main()
{
    // number of terms to
    // find the sum
    int n = 25;
    Console.WriteLine(calculateSum(n));
}
}
 
// This code is contributed
// by inder_verma.


PHP


Javascript


输出:
5875

时间复杂度: O(1)