Java Program to Add the nth Square Series
The series to work on is as follows:
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.
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
Time Complexity: O(1)