📌  相关文章
📜  程序查找系列1 * 3 + 3 * 5 +…的总和。

📅  最后修改于: 2021-04-29 02:06:21             🧑  作者: Mango

给定一系列:

需要找到由S n表示的该系列的前n个项的总和,其中n是给定的输入。
例子

Input : n = 2 
Output : Sn = 18
Explanation:
The sum of first 2 terms of Series is
1*3 + 3*5
= 3 + 15 
= 28

Input : n = 4 
Output : Sn = 116
Explanation:
The sum of first 4 terms of Series is
1*3 + 3*5 + 5*7 + 7*9
= 3 + 15 + 35 + 63
= 116

令,第n项由t n表示。
通过观察可以通过以下方法建立第n个项,可以轻松解决此问题:

现在,系列1、3、5的第n个项由2 * n-1给出
并且系列3、5、7的第n个项由2 * n + 1给出
将这两个值放在t n中

现在,前n个项的总和将由下式给出:

现在,已知级数n * n(1、4、9,…)的前n个项的总和由下式给出:n *(n + 1)*(2 * n + 1)/ 6
并且n个1的总数是n本身。
现在,将值放在S n中

现在,可以通过放置所需的n值轻松找到S n值。
下面是上述方法的实现:

C++
// C++ program to find sum of first n terms
#include 
using namespace std;
 
int calculateSum(int n)
{
    // Sn = n*(4*n*n + 6*n - 1)/3
    return (n * (4 * n * n + 6 * n - 1) / 3);
}
 
int main()
{
    // number of terms to be included in the sum
    int n = 4;
 
    // find the Sn
    cout << "Sum = " << calculateSum(n);
 
    return 0;
}


Java
// Java program to find sum
// of first n terms
class GFG
{
    static int calculateSum(int n)
    {
        // Sn = n*(4*n*n + 6*n - 1)/3
        return (n * (4 * n * n +
                     6 * n - 1) / 3);
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // number of terms to be
        // included in the sum
        int n = 4;
     
        // find the Sn
        System.out.println("Sum = " +
                            calculateSum(n));
    }
}
 
// This code is contributed by Bilal


Python
# Python program to find sum
# of first n terms
def calculateSum(n):
     
    # Sn = n*(4*n*n + 6*n - 1)/3
    return (n * (4 * n * n +
                 6 * n - 1) / 3);
 
# Driver Code
 
# number of terms to be
# included in the sum
n = 4
 
# find the Sn
print("Sum =",calculateSum(n))
 
# This code is contributed by Bilal


C#
// C# program to find sum
// of first n terms
using System;
 
class GFG
{
 
static int calculateSum(int n)
{
    // Sn = n*(4*n*n + 6*n - 1)/3
    return (n * (4 * n * n +
                 6 * n - 1) / 3);
}
 
// Driver code
static public void Main ()
{
    // number of terms to be
    // included in the sum
    int n = 4;
 
    // find the Sn
    Console.WriteLine("Sum = " +
                       calculateSum(n));
}
}
 
// This code is contributed
// by mahadev


PHP


Javascript


输出:
Sum = 116
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”