Given a positive integer N. The task is to find Nth term of the series 5, 13, 37, 109, 325, …..
Examples:
Input: N = 5
Output: 325
Explanation: From the sequence it can be seen that the 5th term is 325Input: N = 1
Output: 5
Explanation: The 1st term of the given sequence is 5
Approach: The sequence formed by using the following pattern. For any value N
TN = 4 * 3N – 1 + N
Below is the implementation of the above approach:
C++
// C++ program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Function to return Nth term // of the series int calcNum(int N) { return 4 * pow(3, N - 1) + 1; } // Driver Code int main() { int N = 5; cout << calcNum(N); return 0; }
Java
// Java program to implement // the above approach import java.util.*; public class GFG { // Function to return Nth term // of the series static int calcNum(int N) { return 4 * (int)Math.pow(3, N - 1) + 1; } // Driver Code public static void main(String args[]) { int N = 5; System.out.println(calcNum(N)); } } // This code is contributed by Samim Hossain Mondal.
Python3
# Python 3 program for the above approach # Function to return Nth term # of the series def calcNum(N): return 4 * pow(3, N - 1) + 1 # Driver Code if __name__ == "__main__": N=5 print(calcNum(N)) # This code is contributed by Abhishek Thakur.
C#
// C# program to implement // the above approach using System; public class GFG{ // Function to return Nth term // of the series static int calcNum(int N) { return 4 * (int)Math.Pow(3, N - 1) + 1; } // Driver Code static public void Main () { int N = 5; Console.Write(calcNum(N)); } } // This code is contributed by SHubham Singh
Javascript
<script> // JavaScript code for the above approach // Function to return Nth term // of the series function calcNum(N) { return 4 * Math.pow(3, N - 1) + 1; } // Driver Code let N = 5; document.write(calcNum(N)); // This code is contributed by Potta Lokesh </script>
325
Time Complexity: O(log2N), where N represents the given integer.
Auxiliary Space: O(1), no extra space is required.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!