Program to find Nth term of the series 2, 4, 3, 4, 15…
Given a number N. The task is to write a program to find the Nth term in the below series as follows:
2, 4, 3, 4, 15...
Examples:
Input: N = 5
Output: 15
Explanation:
For N = 5,
Nth term = ( N * ( (N%2) + (N%3) )
= ( 5 * ( (5%2) + (5%3) )
= ( 5 * ( 1 + 2 )
= 15
Input: N = 4
Output: 4
Generalized Nth term of this series:
Nth term = ( N * ( (N%2) + (N%3) ) )
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int nthTerm( int N)
{
return (N * ((N % 2) + (N % 3)));
}
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 % 3 )));
}
}
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 % 3 )))
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 % 3)));
}
public static void Main()
{
int N = 5;
GFG a = new GFG();
Console.Write( "Nth term for N = " +
N + " : " +
a.nthTerm(N));
}
}
|
PHP
<?php
function nthTerm( $N )
{
return ( $N * (( $N % 2) + ( $N % 3)));
}
$N = 5 ;
echo "Nth term for N = " . $N .
" : " . nthTerm( $N ) ;
?>
|
Javascript
<script>
function nthTerm( N)
{
return (N * ((N % 2) + (N % 3)));
}
let N = 5;
document.write( "Nth term for N = "
+ N + " : "
+ nthTerm(N));
</script>
|
Output:
Nth term for N = 5 : 15
Time Complexity: O(1)
Auxiliary Space: O(1) because using constant variables
Last Updated :
04 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...