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