在系列 0、4、18、48、100 中找到第 N 项……
给定一个系列0, 4, 18, 48, 100 。 . .和一个整数N ,任务是找到系列的第 N 项。
例子:
Input: N = 4
Output: 48
Explanation: As given in the sequence we can see that 4th term is 48
Input: N = 6
Output: 180
方法:考虑以下观察:
For N = 2, the 2nd term is 4, which can be represented as 8 – 4, i.e. 23 – 22
For N = 3, the 3rd term is 18, which can be represented as 27 – 9, i.e. 33 – 32
For N = 4, the 4th term is 18, which can be represented as 27 – 9, i.e. 43 – 42
.
.
.
Similarly, The N-th term of this series can be represented as N3 – N2
因此,对于任何 N,找到 N 的平方并从数字的立方中减去它。
下面是上述方法的实现:
C++
// C++ code to find Nth term of series
// 0, 4, 18, ...
#include
using namespace std;
// Function to find N-th term
// of the series
int getNthTerm(int N)
{
// (pow(N, 3) - pow(N, 2))
return (N * N * N) - (N * N);
}
// Driver Code
int main()
{
int N = 4;
// Get the 8th term of the series
cout << getNthTerm(N);
return 0;
}
Java
// Java code to find Nth term of series
// 0, 4, 18, ...
class GFG
{
// Function to find N-th term
// of the series
public static int getNthTerm(int N)
{
// (pow(N, 3) - pow(N, 2))
return (N * N * N) - (N * N);
}
// Driver Code
public static void main(String args[])
{
int N = 4;
// Get the 8th term of the series
System.out.println(getNthTerm(N));
}
}
// This code is contributed by gfgking
Python3
# Python code to find Nth term of series
# 0, 4, 18, ...
# Function to find N-th term
# of the series
def getNthTerm(N):
# (pow(N, 3) - pow(N, 2))
return (N * N * N) - (N * N);
# Driver Code
N = 4;
# Get the 8th term of the series
print(getNthTerm(N));
# This code is contributed by gfgking
C#
// C# code to find Nth term of series
// 0, 4, 18, ...
using System;
class GFG {
// Function to find N-th term
// of the series
public static int getNthTerm(int N) {
// (pow(N, 3) - pow(N, 2))
return (N * N * N) - (N * N);
}
// Driver Code
public static void Main() {
int N = 4;
// Get the 8th term of the series
Console.Write(getNthTerm(N));
}
}
// This code is contributed by gfgking
Javascript
输出
48
时间复杂度: O(1)
辅助空间: O(1)