求系列 3, 7, 19, 55, 163, 的第 N 项。 . .
给定一个正整数N 。任务是找到系列 3, 7, 19, 55, 163, ….. 的第 N项
例子:
Input: N = 5
Output: 163
Input: N = 1
Output: 3
方法:使用以下模式形成序列。对于任何值 N
TN = 2 * 3N – 1 + 1
插图:
Input: N = 5
Output: 163
Explanation:
TN = 2 * 3N – 1 + 1
= 2 * 35 – 1 + 1
= 2 * 81 + 1
= 162 + 1
= 163
下面是上述方法的实现:
C++
// C++ program to implement
// the above approach
#include
using namespace std;
// Function to return Nth term
// of the series
int calcNum(int N)
{
return 2 * pow(3, N - 1) + 1;
}
// Driver Code
int main()
{
int N = 5;
cout << calcNum(N);
return 0;
}
Java
// Java code to implement the above approach
import java.lang.*;
public class gfg
{
/* Function to return the Nth term of the series */
static int calcNum(int N)
{
return (int)(2*(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 Abhishek Thakur
Python3
# Python3 program to implement
# the above approach
# Function to return Nth term
# of the series
def calcNum(N):
return 2 * (3 ** (N - 1)) + 1
# Driver Code
N = 5
print(calcNum(N))
# This code is contributed by gfgking
C#
// C# code to implement the above approach
using System;
public class gfg
{
/* Function to return the Nth term of the series */
static int calcNum(int N)
{
return (int)(2 * (Math.Pow(3, N - 1))) + 1;
}
// Driver Code
public static void Main(string[] args)
{
int N = 5;
Console.WriteLine(calcNum(N));
}
}
// This code is contributed by Abhishek Thakur
Javascript
输出
163
时间复杂度: O(1)
辅助空间: O(1)