📜  用于添加第 n 个平方系列的Java程序

📅  最后修改于: 2022-05-13 01:54:34.562000             🧑  作者: Mango

用于添加第 n 个平方系列的Java程序

要处理的系列如下:

1^2+2^2+3^2+4^2+...+n^2

插图

Input : N = 4
Output: 30
Explanation: 12 + 22 + 32 + 42
           = 1 + 4 + 9 + 16
           = 30

Input: N = 5
Output: 55
Explanation: 12 + 22 + 32 + 42 + 52
           = 1 + 4 + 9 + 16 + 25
           = 55

方法:这里将提供为系列计算总和的值。为此,标准方法如下:

  • 天真的方法:使用 for 循环计算值
  • 优化方法:使用公式求系列之和。

方法 1:使用循环在循环内的变量强加条件中维护计数。

示例:使用 for 循环对系列求和并计算每个实例的平方。这是最天真的方法。

Java
// Java Program to Add the nth Square Series
 
// Importing java input output libraries
import java.io.*;
 
class GFG {
 
    // Main driven Program
    public static void main(String args[])
        throws IOException
    {
        // Declaring and initializing holding current sum
        int sum = 0;
 
        // Declaring VARIABLE holding term
        // Initializing to random value
        // to show output
        int n = 4;
 
        System.out.println("Enter number of terms:" + n);
 
        // For-loop for Iterating from 1 and Nth term
        for (int i = 1; i <= n; i++) {
 
            // finding square of cuttent term and updating
            // current sum
            sum += (i * i);
        }
 
        // Printing final sum i.e
        // last updated current sum
        System.out.println("Sum for entered N terms:"
                           + sum);
    }
}


Java
// Java Program to Add the nth Square Series
 
// Importing java input output libraries
import java.io.*;
 
class GFG {
   
    // Main driven Program
    public static void main(String args[]) throws IOException {
       
           // Declaring VARIABLE holding term
           // Initializing to random value
           // to show output
           int n = 4;
     
         // Finding sum using formula
        int sum = (n * (n + 1) * (2 * n + 1)) / 6;
         
        // Displaying result
        System.out.println("Sum upto entered N series :"+sum);
    }
}


输出:

30

时间复杂度: O(N)

方法2:在这种方法中,我们将使用下面提到的公式找到系列的总和。该公式可用于求第n平方级数的和,并通过数学归纳法证明其正确性。它比上面说明的要优化得多。

例子:

Java

// Java Program to Add the nth Square Series
 
// Importing java input output libraries
import java.io.*;
 
class GFG {
   
    // Main driven Program
    public static void main(String args[]) throws IOException {
       
           // Declaring VARIABLE holding term
           // Initializing to random value
           // to show output
           int n = 4;
     
         // Finding sum using formula
        int sum = (n * (n + 1) * (2 * n + 1)) / 6;
         
        // Displaying result
        System.out.println("Sum upto entered N series :"+sum);
    }
}

输出:

30

时间复杂度: O(1)