Program to find Sum of the series 1*3 + 3*5 + ….
Given a series:
Sn = 1*3 + 3*5 + 5*7 + …
It is required to find the sum of first n terms of this series represented by Sn, where n is given taken input.
Input : n = 2 Output : S<sub>n</sub> = 18 Explanation: The sum of first 2 terms of Series is 1*3 + 3*5 = 3 + 15 = 18 Input : n = 4 Output : S<sub>n</sub> = 116 Explanation: The sum of first 4 terms of Series is 1*3 + 3*5 + 5*7 + 7*9 = 3 + 15 + 35 + 63 = 116
Let, the n-th term be denoted by tn.
This problem can easily be solved by observing that the nth term can be founded by following method:
tn = (n-th term of (1, 3, 5, … ) )*(nth term of (3, 5, 7, ….))
Now, n-th term of series 1, 3, 5 is given by 2*n-1
and, the n-th term of series 3, 5, 7 is given by 2*n+1
Putting these two values in tn:
tn = (2*n-1)*(2*n+1) = 4*n*n-1
Now, the sum of first n terms will be given by :
Sn = ∑(4*n*n – 1)
Now, it is known that the sum of first n terms of series n*n (1, 4, 9, …) is given by: n*(n+1)*(2*n+1)/6
And sum of n number of 1’s is n itself.
Now, putting values in Sn:
Sn = 4*n*(n+1)*(2*n+1)/6 – n
= n*(4*n*n + 6*n – 1)/3
Now, Sn value can be easily found by putting the desired value of n.
Below is the implementation of the above approach:
Sum = 116
Time Complexity: O(1)
Auxiliary Space: O(1), since no extra space has been taken.
METHOD 2:Using list comprehension .
This program calculates the sum of the series 1*3 + 3*5 + … using a list comprehension to generate the terms of the series and then finding their sum. The input value n determines the number of terms in the series to be generated and added. The sum of the series is then printed as the output.
1.Take input value for n.
2.Generate the series using a list comprehension and store it in the series list.
3.Calculate the sum of the series list using the sum() function and store it in the variable sum.
4.Print the value of sum as the output.
Sum of the series: 116
The time complexity of this program is O(n), where n is the input value. This is because the program generates n terms of the series and then calculates their sum using the sum() function, which has a time complexity of O(n).
The space complexity of this program is also O(n), where n is the input value. This is because the program generates n terms of the series and stores them in the series list, which has a space complexity of O(n). The variable sum also requires constant space, so it does not affect the space complexity.
Please Login to comment...