Given a value n, the task is to find sum of the series (1*2) + (2*3) + (3*4) + ……+ n terms
Examples:
Input: n = 2
Output: 8
Explanation:
(1*2) + (2*3)
= 2 + 6
= 8
Input: n = 3
Output: 20
Explanation:
(1*2) + (2*3) + (2*4)
= 2 + 6 + 12
= 20
Simple Solution One by one add elements recursively.
Below is the implementation
C++
#include <bits/stdc++.h>
using namespace std;
int sum( int n)
{
if (n == 1) {
return 2;
}
else {
return (n * (n + 1) + sum(n - 1));
}
}
int main()
{
int n = 2;
cout << sum(n);
}
|
Java
class Solution {
static int sum( int n)
{
if (n == 1 ) {
return 2 ;
}
else {
return (n * (n + 1 ) + sum(n - 1 ));
}
}
public static void main(String args[])
{
int n = 2 ;
System.out.println(sum(n));
}
}
|
Python3
def sum (n):
if (n = = 1 ):
return 2 ;
else :
return (n * (n + 1 ) + sum (n - 1 ));
n = 2 ;
print ( sum (n));
|
C#
using System;
class Solution {
static int sum( int n)
{
if (n == 1) {
return 2;
}
else {
return (n * (n + 1) + sum(n - 1));
}
}
public static void Main()
{
int n = 2;
Console.WrieLine(sum(n));
}
}
|
PHP
<?php
function sum( $n )
{
if ( $n == 1)
{
return 2;
}
else
{
return ( $n * ( $n + 1) +
sum( $n - 1));
}
}
$n = 2;
echo sum( $n );
?>
|
Javascript
<script>
function sum(n)
{
if (n == 1) {
return 2;
}
else {
return (n * (n + 1) + sum(n - 1));
}
}
n = 2;
document.write(sum(n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n), since n extra space has been taken.
Efficient Solution We can solve this problem using direct formula.
Sum can be written as below
?(n * (n+1))
?(n*n + n)
= ?(n*n) + ?(n)
We can apply the formulas for sum squares of natural number and sum of natural numbers.
= n(n+1)(2n+1)/6 + n*(n+1)/2
= n * (n + 1) * (n + 2) / 3
C++
#include <bits/stdc++.h>
using namespace std;
int sum( int n)
{
return n * (n + 1) * (n + 2) / 3;
}
int main()
{
int n = 2;
cout << sum(n);
}
|
Java
class GFG
{
static int sum( int n)
{
return n * (n + 1 ) * (n + 2 ) / 3 ;
}
public static void main(String[] args)
{
int n = 2 ;
System.out.println(sum(n));
}
}
|
Python3
def Sum (n):
return n * (n + 1 ) * (n + 2 ) / / 3
if __name__ = = "__main__" :
n = 2 ;
print ( Sum (n))
|
C#
using System;
class GFG
{
static int sum( int n)
{
return n * (n + 1) * (n + 2) / 3;
}
public static void Main(String[] args)
{
int n = 2;
Console.WriteLine(sum(n));
}
}
|
PHP
<?php
function sum( $n )
{
return $n * ( $n + 1) * ( $n + 2) / 3;
}
$n = 2;
echo sum( $n );
?>
|
Javascript
<script>
function sum(n)
{
return n * (n + 1) * (n + 2) / 3;
}
var n = 2;
document.write(sum(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!