Program to find the Nth term of the series 3, 7, 13, 21, 31…..
Last Updated :
12 Nov, 2023
Given a number N, the task is to find the Nth term of this series:
3, 7, 13, 21, 31, …….
Examples:
Input: N = 4
Output: 21
Explanation:
Nth term = (pow(N, 2) + N + 1)
= (pow(4, 2) + 4 + 1)
= 21
Input: N = 11
Output: 133
Approach:
Subtracting these two equations we get
Therefore, the Nth Term of the given series is:
Below is the implementation of the above approach:
C++
#include <iostream>
#include <math.h>
using namespace std;
long long int getNthTerm( long long int N)
{
return ( pow (N, 2) + N + 1);
}
int main()
{
long long int N = 11;
cout << getNthTerm(N);
return 0;
}
|
Java
import java.util.*;
class solution
{
static long getNthTerm( long N)
{
return (( int )Math.pow(N, 2 ) + N + 1 );
}
public static void main(String arr[])
{
long N = 11 ;
System.out.println(getNthTerm(N));
}
}
|
Python3
def getNthTerm(N):
return ( pow (N, 2 ) + N + 1 )
if __name__ = = '__main__' :
N = 11
print (getNthTerm(N))
|
C#
using System;
class GFG
{
static long getNthTerm( long N)
{
return (( int )Math.Pow(N, 2) + N + 1);
}
static public void Main ()
{
long N = 11;
Console.Write(getNthTerm(N));
}
}
|
Javascript
<script>
function getNthTerm(N)
{
return (Math.pow(N, 2) + N + 1);
}
let N = 11;
document.write(getNthTerm(N));
</script>
|
PHP
<?php
function getNthTerm( $N )
{
return (pow( $N , 2) + $N + 1);
}
$N = 11;
echo getNthTerm( $N );
?>
|
Time Complexity: O(1)
Space Complexity: O(1) since using constant variables
Method 2: We can also solve the problem by the formula [ (n+1)2-n ].
C++
#include <iostream>
#include <math.h>
using namespace std;
long long int getNthTerm( long long int N)
{
return ( pow (N + 1, 2) - N);
}
int main()
{
long long int N = 11;
cout << getNthTerm(N);
return 0;
}
|
Java
public class Main {
static long getNthTerm( long N) {
return ( long ) (Math.pow(N + 1 , 2 ) - N);
}
public static void main(String[] args) {
long N = 11 ;
System.out.println(getNthTerm(N));
}
}
|
Python3
import math
def getNthTerm(N):
return int (math. pow (N + 1 , 2 ) - N)
if __name__ = = '__main__' :
N = 11
print (getNthTerm(N))
|
C#
using System;
class Program {
static long GetNthTerm( long N)
{
return ( long )(Math.Pow(N + 1, 2) - N);
}
static void Main()
{
long N = 11;
Console.WriteLine(GetNthTerm(N));
}
}
|
Javascript
function getNthTerm(N) {
return Math.pow(N + 1, 2) - N;
}
const N = 11;
console.log(getNthTerm(N));
|
Time Complexity: O(logN)
Space Complexity: O(1) since using constant variables
Share your thoughts in the comments
Please Login to comment...