Java Program to Add the nth Square Series
Last Updated :
16 Aug, 2022
The series to work on is as follows:
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
import java.io.*;
class GFG {
public static void main(String args[])
throws IOException
{
int sum = 0 ;
int n = 4 ;
System.out.println( "Enter number of terms:" + n);
for ( int i = 1 ; i <= n; i++) {
sum += (i * i);
}
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
import java.io.*;
class GFG {
public static void main(String args[]) throws IOException {
int n = 4 ;
int sum = (n * (n + 1 ) * ( 2 * n + 1 )) / 6 ;
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...