Find Nth term of the series 0, 2, 4, 8, 12, 18…
Last Updated :
16 Aug, 2022
Given a number N. The task is to write a program to find the Nth term in the below series:
0, 2, 4, 8, 12, 18…
Examples:
Input: 3
Output: 4
For N = 3
Nth term = ( 3 + ( 3 - 1 ) * 3 ) / 2
= 4
Input: 5
Output: 12
On observing carefully, the Nth term in the above series can be generalized as:
Nth term = ( N + ( N - 1 ) * N ) / 2
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int nthTerm( int N)
{
return (N + N * (N - 1)) / 2;
}
int main()
{
int N = 5;
cout << nthTerm(N);
return 0;
}
|
Java
import java.io.*;
class GFG {
public static int nthTerm( int N)
{
return (N + (N - 1 ) * N) / 2 ;
}
public static void main(String[] args)
{
int N = 5 ;
System.out.println(nthTerm(N));
}
}
|
Python 3
def nthTerm(N) :
return (N + N * (N - 1 )) / / 2
if __name__ = = "__main__" :
N = 5
print (nthTerm(N))
|
C#
using System;
class gfg
{
public int nthTerm( int N)
{
int n = ((N + N * (N - 1)) / 2);
return n;
}
static void Main( string [] args)
{
gfg p = new gfg();
int a = p.nthTerm(5);
Console.WriteLine(a);
Console.Read();
}
}
|
PHP
<?php
function nthTerm( $N )
{
return (int)(( $N + $N *
( $N - 1)) / 2);
}
$N = 5;
echo nthTerm( $N );
?>
|
Javascript
<script>
function nthTerm(N)
{
return parseInt((N + N * (N - 1)) / 2);
}
let N = 5;
document.write(nthTerm(N));
</script>
|
Time Complexity: O(1)
Auxiliary space: O(1) as it is using constant variables
Share your thoughts in the comments
Please Login to comment...