Program to find Nth term of the series 3, 6, 18, 24, …
Given a number N. The task is to write a program to find the Nth term in the below series:
3, 6, 18, 24, 45, 54...(Nth term)
Examples:
Input: N = 5
Output: 45
Explanation:
For N = 5,
Nth term = ( N * ( (N/2) + ( (N%2) * 2) + N )
= ( 5 * ( (5/2) + ( (5%2) * 2) + 5 )
= ( 5 * ( 2 + ( 1 * 2) + 5 )
= 45
Input : 6
Output : 54
Generalized Nth term of this series:
Nth term = ( N * ( (N/2) + ((N%2) * 2) + N )
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int nthTerm( int N)
{
return (N * ((N / 2) + ((N % 2) * 2) + N));
}
int main()
{
int N = 5;
cout << "Nth term for N = "
<< N << " : "
<< nthTerm(N);
return 0;
}
|
Java
import java.io.*;
class Nth {
public int nthTerm( int N)
{
return (N * ((N / 2 ) + ((N % 2 ) * 2 ) + N));
}
}
class GFG {
public static void main(String[] args)
{
int N = 5 ;
Nth a = new Nth();
System.out.println( "Nth term for N = "
+ N + " : "
+ a.nthTerm(N));
}
}
|
Python3
def nthTerm( N):
return (N * ((N / / 2 ) + ((N % 2 ) * 2 ) + N))
if __name__ = = '__main__' :
N = 5
print ( "Nth term for N = " , N , " : " , nthTerm(N))
|
C#
using System;
class GFG
{
public int nthTerm( int N)
{
return (N * ((N / 2) +
((N % 2) * 2) + N));
}
public static void Main()
{
int N = 5;
GFG a = new GFG();
Console.WriteLine( "Nth term for N = " +
N + " : " +
a.nthTerm(N));
}
}
|
PHP
<?php
function nthTerm( $N )
{
return ( $N * ((int)( $N / 2) +
(( $N % 2) * 2) + $N ));
}
$N = 5;
echo "Nth term for N = " , $N ,
" : " , nthTerm( $N );
?>
|
Javascript
<script>
function nthTerm( N)
{
return parseInt(N * (parseInt(N / 2) + ((N % 2) * 2) + N));
}
let N = 5;
document.write( "Nth term for N = "
+ N + " : "
+ nthTerm(N));
</script>
|
Output:
Nth term for N = 5 : 45
Time Complexity: O(1)
Auxiliary Space: O(1) because using constant variables
Last Updated :
08 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...