Program to find Sum of the series 1*3 + 3*5 + ....
Last Updated :
21 Sep, 2023
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.
Examples:
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)
=∑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:
C++
// C++ program to find sum of first n terms
#include <bits/stdc++.h>
using namespace std;
int calculateSum(int n)
{
// Sn = n*(4*n*n + 6*n - 1)/3
return (n * (4 * n * n + 6 * n - 1) / 3);
}
int main()
{
// number of terms to be included in the sum
int n = 4;
// find the Sn
cout << "Sum = " << calculateSum(n);
return 0;
}
Java
// Java program to find sum
// of first n terms
class GFG
{
static int calculateSum(int n)
{
// Sn = n*(4*n*n + 6*n - 1)/3
return (n * (4 * n * n +
6 * n - 1) / 3);
}
// Driver Code
public static void main(String args[])
{
// number of terms to be
// included in the sum
int n = 4;
// find the Sn
System.out.println("Sum = " +
calculateSum(n));
}
}
// This code is contributed by Bilal
Python
# Python program to find sum
# of first n terms
def calculateSum(n):
# Sn = n*(4*n*n + 6*n - 1)/3
return (n * (4 * n * n +
6 * n - 1) / 3);
# Driver Code
# number of terms to be
# included in the sum
n = 4
# find the Sn
print("Sum =",calculateSum(n))
# This code is contributed by Bilal
C#
// C# program to find sum
// of first n terms
using System;
class GFG
{
static int calculateSum(int n)
{
// Sn = n*(4*n*n + 6*n - 1)/3
return (n * (4 * n * n +
6 * n - 1) / 3);
}
// Driver code
static public void Main ()
{
// number of terms to be
// included in the sum
int n = 4;
// find the Sn
Console.WriteLine("Sum = " +
calculateSum(n));
}
}
// This code is contributed
// by mahadev
JavaScript
<script>
// Javascript program to find sum
// of first n terms
function calculateSum( n) {
// Sn = n*(4*n*n + 6*n - 1)/3
return (n * (4 * n * n + 6 * n - 1) / 3);
}
// Driver Code
// number of terms to be
// included in the sum
let n = 4;
// find the Sn
document.write("Sum = " + calculateSum(n));
// This code contributed by Princi Singh
</script>
PHP
<?php
// PHP program to find sum
// of first n terms
function calculateSum($n)
{
// Sn = n*(4*n*n + 6*n - 1)/3
return ($n * (4 * $n * $n +
6 * $n - 1) / 3);
}
// number of terms to be
// included in the sum
$n = 4;
// find the Sn
echo "Sum = " . calculateSum($n);
// This code is contributed
// by ChitraNayal
?>
Time Complexity: O(1)
Auxiliary Space: O(1), since no extra space has been taken.
METHOD 2:Using list comprehension .
APPROACH:
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.
ALGORITHM:
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.
C++
#include <iostream>
#include <vector>
int main() {
int n = 4;
std::vector<int> series;
// Generate the series using list comprehension
for (int i = 0; i < n; i++) {
int term = (2 * i + 1) * (2 * i + 3);
series.push_back(term);
}
// Calculate the sum of the series
int sum = 0;
for (int i = 0; i < series.size(); i++) {
sum += series[i];
}
// Print the sum
std::cout << "Sum of the series: " << sum << std::endl;
return 0;
}
// This code is contributed by uomkar369
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
/**
* This program generates the series of 2 * i + 1 * (2 * i + 3) for i in range(0, n).
*
* @param n The number of terms in the series.
*/
public static void main(String[] args) {
int n = 4; // The number of terms in the series.
// Generate the series.
List<Integer> series = new ArrayList<>(); // A list to store the terms of the series.
for (int i = 0; i < n; i++) { // Iterate over the number of terms.
int term = (2 * i + 1) * (2 * i + 3); // Calculate the term of the series.
series.add(term); // Add the term to the list.
}
// Calculate the sum of the series.
int sum = 0; // The sum of the series.
for (int i = 0; i < series.size(); i++) { // Iterate over the list of terms.
sum += series.get(i); // Add the current term to the sum.
}
// Print the sum.
System.out.println("Sum of the series: " + sum); // Print the sum of the series.
}
}
Python3
# Using a list comprehension
n = 4
series = [(2*i+1)*(2*i+3) for i in range(n)]
sum = sum(series)
print("Sum of the series:", sum)
C#
using System;
using System.Collections.Generic;
class GFG
{
static void Main()
{
int n = 4;
List<int> series = new List<int>();
// Generate the series using list comprehension
for (int i = 0; i < n; i++)
{
int term = (2 * i + 1) * (2 * i + 3);
series.Add(term);
}
// Calculate the sum of the series
int sum = 0;
foreach (int item in series)
{
sum += item;
}
// Print the sum
Console.WriteLine("Sum of the series: " + sum);
}
}
// This code is contributed by uomkar369
JavaScript
let n = 4;
let series = new Array();
// Generate the series using list comprehension
for (let i = 0; i < n; i++) {
let term = (2 * i + 1) * (2 * i + 3);
series.push(term);
}
// Calculate the sum of the series
let sum = 0;
for (let i = 0; i < series.length; i++) {
sum += series[i];
}
// Prlet the sum
document.write("Sum of the series: " + sum);
OutputSum of the series: 116
Time Complexity:
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).
Space Complexity:
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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem