Find n-th term of series 3, 9, 21, 41, 71…
Last Updated :
22 Jun, 2022
Given a mathematical series as 3, 9, 21, 41, 71… For a given integer n, you have to find the nth number of this series.
Examples :
Input : n = 4
Output : 41
Input : n = 2
Output : 9
Our first task for solving this problem is to crack the series. If you will gave a closer look on the series, for a general n-th term the value will be (?n2)+(?n)+1, where
So, for calculating any n-th term of given series say f(n) we have:
f(n) = (?n2)+(?n)+1
= ( ((n*(n+1)*(2n+1))/6) + (n*(n+1)/2) + 1
= (n3+ 3n2 + 2n + 3 ) /3
C++
#include <bits/stdc++.h>
using namespace std;
int seriesFunc( int n)
{
int sumSquare = (n * (n + 1)
* (2 * n + 1)) / 6;
int sumNatural = (n * (n + 1) / 2);
return (sumSquare + sumNatural + 1);
}
int main()
{
int n = 8;
cout << seriesFunc(n) << endl;
n = 13;
cout << seriesFunc(13);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int seriesFunc( int n)
{
int sumSquare = (n * (n + 1 )
* ( 2 * n + 1 )) / 6 ;
int sumNatural = (n * (n + 1 ) / 2 );
return (sumSquare + sumNatural + 1 );
}
public static void main(String args[])
{
int n = 8 ;
System.out.println(seriesFunc(n));
n = 13 ;
System.out.println(seriesFunc( 13 ));
}
}
|
Python3
def seriesFunc(n):
sumSquare = (n * (n + 1 ) *
( 2 * n + 1 )) / 6
sumNatural = (n * (n + 1 ) / 2 )
return (sumSquare + sumNatural + 1 )
n = 8
print ( int (seriesFunc(n)))
n = 13
print ( int (seriesFunc(n)))
|
C#
using System;
class GFG
{
static int seriesFunc( int n)
{
int sumSquare = (n * (n + 1)
* (2 * n + 1)) / 6;
int sumNatural = (n * (n + 1) / 2);
return (sumSquare + sumNatural + 1);
}
public static void Main()
{
int n = 8;
Console.WriteLine(seriesFunc(n));
n = 13;
Console.WriteLine(seriesFunc(13));
}
}
|
PHP
<?php
function seriesFunc( $n )
{
$sumSquare = ( $n * ( $n + 1)
* (2 * $n + 1)) / 6;
$sumNatural = ( $n * ( $n + 1) / 2);
return ( $sumSquare + $sumNatural + 1);
}
$n = 8;
echo (seriesFunc( $n ) . "\n" );
$n = 13;
echo (seriesFunc( $n ) . "\n" );
?>
|
Javascript
<script>
function seriesFunc(n)
{
let sumSquare = (n * (n + 1)
* (2 * n + 1)) / 6;
let sumNatural = (n * (n + 1) / 2);
return (sumSquare + sumNatural + 1);
}
let n = 8;
document.write(seriesFunc(n) + "<br/>" );
n = 13;
document.write(seriesFunc(13));
</script>
|
Output :
241
911
Time Complexity: O(1) since constant operations are performed
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...