📜  前N个Pronic数的总和

📅  最后修改于: 2021-05-06 07:34:18             🧑  作者: Mango

给定数字N ,任务是找到前N个Pronic数的总和。

例子:

方法:

    令,第N项由T N表示。可以通过如下拆分每个术语来轻松解决此问题:

    S_N = 0 + 2 + 6 + 12 + 20 + 30......
    S_N = (0 * 1) + (1 * 2) + (2 * 3) + (3 * 4) + (4 * 5) + ......
    S_N = (0 * (0 + 1) + (1 * (1 + 1)) + (2 * (2 + 1)) + (3 * (3 + 1)) + (4 * (4 + 1)) + ......
    S_N = (0^2 + 0) + (1^2 + 1) + (2^2 + 2) + (3^2 + 3) + (4^2 + 4) +......
    S_N = (0 + 1 + 2 + 3 + 4 + ...T_N) + (0^2 + 1^2 + 2^2 + 3^2 + 4^2 + ... T_N)

    所以:

    下面是上述方法的实现:

    C++
    // C++ implementation to find 
    // sum of first N terms
    #include 
    using namespace std;
      
    // Function to calculate the sum
    int calculateSum(int N)
    {
      
        return N * (N - 1) / 2
               + N * (N - 1)
                     * (2 * N - 1) / 6;
    }
      
    // Driver code
    int main()
    {
        int N = 3;
      
        cout << calculateSum(N);
      
        return 0;
    }


    Java
    // Java implementation implementation to find 
    // sum of first N terms 
    class GFG{ 
          
    // Function to calculate the sum 
    static int calculateSum(int N) 
    { 
          
        return N * (N - 1) / 2 + N * (N - 1) *
               (2 * N - 1) / 6; 
    } 
          
    // Driver code 
    public static void main (String[] args) 
    { 
        int N = 3; 
          
        System.out.println(calculateSum(N)); 
    } 
    } 
      
    // This code is contributed by Pratima Pandey


    Python3
    # Python3 implementation to find 
    # sum of first N terms
      
    # Function to calculate the sum
    def calculateSum(N):
      
        return (N * (N - 1) // 2 + 
                N * (N - 1) * (2 * 
                     N - 1) // 6);
      
    # Driver code
    N = 3;
    print(calculateSum(N));
      
    # This code is contributed by Code_Mech


    C#
    // C# implementation implementation to find 
    // sum of first N terms 
    using System;
    class GFG{ 
          
    // Function to calculate the sum 
    static int calculateSum(int N) 
    { 
          
        return N * (N - 1) / 2 + N * (N - 1) *
                            (2 * N - 1) / 6; 
    } 
          
    // Driver code 
    public static void Main() 
    { 
        int N = 3; 
          
        Console.Write(calculateSum(N)); 
    } 
    } 
      
    // This code is contributed by Code_Mech


    输出:
    8
    

    时间复杂度: O(1)。