求系列 3, 7, 14, 27, 52, 的第 N 项。 . .
给定一个正整数N 。任务是找到系列3, 7, 14, 27, 52, …..的第 N项
例子:
Input: N = 5
Output: 52
Input: N = 1
Output: 3
方法:
该序列是通过使用以下模式形成的。对于任何值 N-
TN = (N -1) + 3 * 2N-1
插图:
Input: N = 5
Output: 52
Explanation:
TN = (5 – 1) + 3 * 25 – 1
= 4 + 3 * 16
= 52
下面是上述方法的实现:
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 ((N - 1) + 3 *
pow(2, N - 1));
}
// Driver Code
int main()
{
int N = 5;
cout << calcNum(N);
return 0;
}
Java
// Java program to implement
// the above approach
class GFG
{
// Function to return Nth term
// of the series
static int calcNum(int N) {
return (int) ((N - 1) + 3 * Math.pow(2, N - 1));
}
// Driver Code
public static void main(String args[]) {
int N = 5;
System.out.println(calcNum(N));
}
}
// This code is contributed by saurabh_jaiswal.
Python3
# Python code for the above approach
# Function to return Nth term
# of the series
def calcNum(N):
return ((N - 1) + 3 * (2 ** (N - 1)));
# Driver Code
N = 5;
print(calcNum(N));
# This code is contributed by Saurabh Jaiswal
C#
// C# program to implement
// the above approach
using System;
class GFG {
// Function to return Nth term
// of the series
static int calcNum(int N)
{
return (int)((N - 1) + 3 * Math.Pow(2, N - 1));
}
// Driver Code
public static void Main()
{
int N = 5;
Console.WriteLine(calcNum(N));
}
}
// This code is contributed by ukasp.
Javascript
输出
52
时间复杂度: O(1)
辅助空间: O(1)