Find Nth term of the series 1, 1, 2, 6, 24…
Given a number N. The task is to write a program to find the Nth term in the below series:
1, 1, 2, 6, 24…
Examples:
Input: 3
Output: 2
For N = 3
Nth term = (N-1)!
= 2
Input: 5
Output: 24
Nth term of the series is given by below formula:
Nth term = ( N-1)!
Below is the required implementation:
C++
#include <iostream>
using namespace std;
int nthTerm( int N)
{
if (N <= 1)
return 1;
int i, fact = 1;
for (i = 1; i < N; i++)
fact = fact * i;
return fact;
}
int main()
{
int N = 3;
cout << nthTerm(N);
return 0;
}
|
Java
import java.io.*;
class Nth {
public int nthTerm( int N)
{
if (N <= 1 )
return 1 ;
int i, fact = 1 ;
for (i = 1 ; i < N; i++)
fact = fact * i;
return fact;
}
}
class GFG {
public static void main(String[] args)
{
int N = 3 ;
Nth a = new Nth();
System.out.println(a.nthTerm(N));
}
}
|
Python 3
def nthTerm(n) :
if n < = 1 :
return 1
fact = 1
for i in range ( 1 , N) :
fact = fact * i
return fact
if __name__ = = "__main__" :
N = 3
print (nthTerm(N))
|
C#
using System;
class GFG
{
public int nthTerm( int N)
{
if (N <= 1)
return 1;
int i, fact = 1;
for (i = 1; i < N; i++)
fact = fact * i;
return fact;
}
public static void Main()
{
int N = 3;
GFG a = new GFG();
Console.Write(a.nthTerm(N));
}
}
|
PHP
<?php
function nthTerm( $N )
{
if ( $N <= 1)
return 1;
$fact = 1;
for ( $i = 1; $i < $N ; $i ++)
$fact = $fact * $i ;
return $fact ;
}
$N = 3;
echo nthTerm( $N );
?>
|
Javascript
<script>
function nthTerm( N)
{
if (N <= 1)
return 1;
let i, fact = 1;
for (i = 1; i < N; i++)
fact = fact * i;
return fact;
}
let N = 3;
document.write(nthTerm(N));
</script>
|
Time Complexity: O(N), where N represents the given integer.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Last Updated :
23 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...