Program to find nth term of the series 1 4 15 24 45 60 92
Last Updated :
23 Jun, 2022
Given a number n, the task is to find the nth term of the series
1, 4, 15, 24, 45, 60, 91, 112, 153…..
where 0 < n < 100000000.
Examples:
Input: n = 10
Output: 180
Input: n = 5
Output: 45
Approach:
The idea is very simple but hard to recognise.
If n is odd, the nth term will be [ ( 2 * ( n^2 ) ) – n ].
If n is even, the nth term will be [ 2 * ( (n^2) – n ) ].
Implementation:
C++
#include <stdio.h>
long long int nthTerm( long long int n)
{
long long int nth;
if (n % 2 == 0)
nth = 2 * ((n * n) - n);
else
nth = (2 * n * n) - n;
return nth;
}
int main()
{
long long int n;
n = 5;
printf ( "%lld\n" , nthTerm(n));
n = 25;
printf ( "%lld\n" , nthTerm(n));
n = 25000000;
printf ( "%lld\n" , nthTerm(n));
n = 250000007;
printf ( "%lld\n" , nthTerm(n));
return 0;
}
|
Java
class GFG
{
static long nthTerm( long n)
{
long nth;
if (n % 2 == 0 )
nth = 2 * ((n * n) - n);
else
nth = ( 2 * n * n) - n;
return nth;
}
public static void main(String []args)
{
long n;
n = 5 ;
System.out.println(nthTerm(n));
n = 25 ;
System.out.println(nthTerm(n));
n = 25000000 ;
System.out.println(nthTerm(n));
n = 250000007 ;
System.out.println(nthTerm(n));
}
}
|
Python3
def nthTerm(n):
nth = 0
if (n % 2 = = 0 ):
nth = 2 * ((n * n) - n)
else :
nth = ( 2 * n * n) - n
return nth
n = 5
print (nthTerm(n))
n = 25
print (nthTerm(n))
n = 25000000
print (nthTerm(n))
n = 250000007
print (nthTerm(n))
|
C#
using System;
class GFG
{
static long nthTerm( long n)
{
long nth;
if (n % 2 == 0)
nth = 2 * ((n * n) - n);
else
nth = (2 * n * n) - n;
return nth;
}
public static void Main()
{
long n;
n = 5;
Console.WriteLine(nthTerm(n));
n = 25;
Console.WriteLine(nthTerm(n));
n = 25000000;
Console.WriteLine(nthTerm(n));
n = 250000007;
Console.WriteLine(nthTerm(n));
}
}
|
PHP
<?php
function nthTerm( $n )
{
$nth ;
if ( $n % 2 == 0)
$nth = 2 * (( $n * $n ) - $n );
else
$nth = (2 * $n * $n ) - $n ;
return $nth ;
}
$n = 5;
echo nthTerm( $n ), "\n" ;
$n = 25;
echo nthTerm( $n ), "\n" ;
$n = 25000000;
echo nthTerm( $n ), "\n" ;
$n = 250000007;
echo nthTerm( $n ), "\n" ;
?>
|
Javascript
<script>
function nthTerm( n)
{
let nth;
if (n % 2 == 0)
nth = 2 * ((n * n) - n);
else
nth = (2 * n * n) - n;
return nth;
}
let n = 5;
document.write( nthTerm(n) + "<br/>" );
n = 25;
document.write( nthTerm(n) + "<br/>" );
n = 25000000;
document.write( nthTerm(n) + "<br/>" );
n = 250000007;
document.write( nthTerm(n) + "<br/>" );
</script>
|
Output:
45
1225
1249999950000000
125000006750000091
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...