Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaJava Program to Add the nth Square Series

Java Program to Add the nth Square Series

The series to work on is as follows:

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

Illustration

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

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 nth Square Series and its correctness can be proved through mathematical induction. It is much more optimized the above illustrated. 

12 + 22 + 32 + … + n2 = 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)

Auxiliary space: O(1) as it is using constant variables

RELATED ARTICLES

Most Popular

Recent Comments