# Java Program to Add the nth Square Series

The series to work on is as follows:

**Illustration**

Input :N = 4Output:30Explanation:1^{2}+ 2^{2}+ 3^{2}+ 4^{2}= 1 + 4 + 9 + 16 = 30Input:N = 5Output:55Explanation:1^{2}+ 2^{2}+ 3^{2}+ 4^{2}+ 5^{2}= 1 + 4 + 9 + 16 + 25 = 55

**Approaches: **Here will be provided with the value up to which sum is computed for the series. in order to do so standard approaches are as follows:

**Naive Approach:**Using for loop to compute the value**Optimize Method:**Using the formula to find the sum of the series.

**Approach 1: **Using loops a maintaining a count in a variable imposing condition inside the loop.

**Example: **Sum of the series by using for loop and calculate the square at each instance. This is the most naive approach.

## 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 current 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);` ` ` `}` `}` |

**Output:**

30

**Time Complexity:** O(N)

**Approach 2: **In this approach, we will find the sum of the series by using the formula mentioned below. This formula can be used to find the sum of the n^{th} Square Series and its correctness can be proved through mathematical induction. It is much more optimized the above illustrated.

1

^{2 }+ 2^{2 }+ 3^{2}+ … + n^{2}= n * (n + 1) * (2 * (n + 1))/6

**Example:**

## 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);` ` ` `}` `}` |

**Output:**

30

**Time Complexity:** O(1)