Find Nth term of the series 0, 1, 1, 2, 5, 29, 841…
Last Updated :
10 Jan, 2022
Given a positive integer N, the task is to find the Nth term in the series 0, 1, 1, 2, 5, 29, 841…
Examples:
Input: N = 6
Output: 29
Explanation: The 6th term of the given series is 29.
Input: N = 1
Output: 1
Input: N = 8
Output: 750797
Approach: The given problem is a basic maths-based problem where the Ai = Ai-12 + Ai-22. Therefore, create variables a = 0 and b = 1. Iterate using the variable i in the range [2, N], and for each i, calculate the ith term and update the value of a and b to i – 1th and i – 2th term respectively.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getNthTerm( int N)
{
if (N < 3)
return N - 1;
long int a = 0, b = 1;
for ( int i = 3; i <= N; i++) {
long int c = a * a + b * b;
a = b;
b = c;
}
return b;
}
int main()
{
int N = 8;
cout << getNthTerm(N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int getNthTerm( int N)
{
if (N < 3 )
return N - 1 ;
int a = 0 , b = 1 ;
for ( int i = 3 ; i <= N; i++) {
int c = a * a + b * b;
a = b;
b = c;
}
return b;
}
public static void main(String[] args)
{
int N = 8 ;
System.out.print(getNthTerm(N));
}
}
|
Python3
def getNthTerm(N):
if (N < 3 ):
return N - 1
a = 0
b = 1
for i in range ( 3 , N + 1 ):
c = a * a + b * b
a = b
b = c
return b
N = 8
print (getNthTerm(N))
|
C#
using System;
class GFG
{
static int getNthTerm( int N)
{
if (N < 3)
return N - 1;
long a = 0, b = 1;
for ( int i = 3; i <= N; i++) {
long c = a * a + b * b;
a = b;
b = c;
}
return ( int )b;
}
public static void Main()
{
int N = 8;
Console.Write(getNthTerm(N));
}
}
|
Javascript
<script>
function getNthTerm(N) {
if (N < 3)
return N - 1;
let a = 0, b = 1;
for (let i = 3; i <= N; i++) {
let c = a * a + b * b;
a = b;
b = c;
}
return b;
}
let N = 8;
document.write(getNthTerm(N));
</script>
|
Time complexity: O(N)
Auxiliary space: O(1)
Share your thoughts in the comments
Please Login to comment...