Find Nth term of the series 2, 3, 10, 15, 26….
Last Updated :
20 Aug, 2022
Given a number N, the task is to find the Nth term in series 2, 3, 10, 15, 26….
Example:
Input: N = 2
Output: 3
2nd term = (2*2)-1
= 3
Input: N = 5
Output: 26
5th term = (5*5)+1
= 26
Approach:
- Nth number of the series is obtained by
- Squaring the number itself.
- If the number is odd, add 1 to the squared number. And, subtract 1 if the number is even
- Since the starting number of the series is 2
1st term = 2
2nd term = (2 * 2) – 1 = 3
3rd term = (3 * 3) + 1 = 10
4th term = (4 * 4) – 1 = 15
5th term = (5 * 5) + 1 = 26
and so on….
- In general, Nth number is obtained by formula:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int nthTerm( int N)
{
int nth = 0;
if (N % 2 == 1)
nth = (N * N) + 1;
else
nth = (N * N) - 1;
return nth;
}
int main()
{
int N = 5;
cout << nthTerm(N) << endl;
return 0;
}
|
Java
class GFG
{
static int nthTerm( int N)
{
int nth = 0 ;
if (N % 2 == 1 )
nth = (N * N) + 1 ;
else
nth = (N * N) - 1 ;
return nth;
}
public static void main(String[] args)
{
int N = 5 ;
System.out.print(nthTerm(N) + "\n" );
}
}
|
Python3
def nthTerm(N) :
nth = 0 ;
if (N % 2 = = 1 ) :
nth = (N * N) + 1 ;
else :
nth = (N * N) - 1 ;
return nth;
if __name__ = = "__main__" :
N = 5 ;
print (nthTerm(N)) ;
|
C#
using System;
class GFG
{
static int nthTerm( int N)
{
int nth = 0;
if (N % 2 == 1)
nth = (N * N) + 1;
else
nth = (N * N) - 1;
return nth;
}
public static void Main(String[] args)
{
int N = 5;
Console.Write(nthTerm(N) + "\n" );
}
}
|
Javascript
<script>
function nthTerm(N)
{
let nth = 0;
if (N % 2 == 1)
nth = (N * N) + 1;
else
nth = (N * N) - 1;
return nth;
}
let N = 5;
document.write(nthTerm(N));
</script>
|
Time Complexity: O(1) since no loop is used the algorithm takes up constant time to perform the operations
Auxiliary Space: O(1) since no extra array is used so the space taken by the algorithm is constant
Share your thoughts in the comments
Please Login to comment...