求系列 2、8、18、32、50…的第 N 项
给定数列 2、8、18、32、50……,求数列的第 N 项。
例子:
Input: N = 1
Output: 2
Input: N = 3
Output: 18
Input: N = 5
Output: 50
方法:
为了找到第 n 项,我们需要找到 n 与每个项之间的关系。
1st term = 2 = 2*(12) // 2*first perfect square
2nd term = 8 = 2*(22) // 2*second perfect square
3rd term = 18 = 2*(32) // 2*third perfect square
4th term = 32 = 2*(42) // 2*fourth perfect square
.
.
.
.
.
Nth term = 2*(Nth perfect square)
公式-
TN = 2 * N ^ 2
插图-
Input: N = 5
Output: 50
Explanation-
TN = 2 * N ^ 2
= 2* 5 ^ 2
= 2 * 25
= 50
下面是实现上述方法的 C++ 程序——
C++
// C++ program to implement
// the above approach
#include
using namespace std;
// Find n-th term of series
// 2, 8, 18, 32, 50...
int nthTerm(int N)
{
// Nth perfect square is N * N
int Nthperfectsquare = N * N;
return 2 * Nthperfectsquare;
}
// Driver code
int main()
{
int N = 5;
cout << nthTerm(N) << endl;
return 0;
}
Java
// Java code for the above approach
import java.io.*;
class GFG {
// Find n-th term of series
// 2, 8, 18, 32, 50...
static int nthTerm(int N)
{
// Nth perfect square is N * N
int Nthperfectsquare = N * N;
return 2 * Nthperfectsquare;
}
// Driver code
public static void main (String[] args) {
int N = 5;
System.out.println(nthTerm(N));
}
}
// This code is contributed by Potta Lokesh
Python
# Python program to implement
# the above approach
# Find n-th term of series
# 2, 8, 18, 32, 50...
def nthTerm(N):
# Nth perfect square is N * N
Nthperfectsquare = N * N
return 2 * Nthperfectsquare
# Driver Code
if __name__ == "__main__":
N = 5
print(nthTerm(N))
# This code is contributed by Samim Hossain Mondal.
C#
using System;
public class GFG{
// Find n-th term of series
// 2, 8, 18, 32, 50...
static int nthTerm(int N)
{
// Nth perfect square is N * N
int Nthperfectsquare = N * N;
return 2 * Nthperfectsquare;
}
// Driver code
static public void Main (){
int N = 5;
Console.Write(nthTerm(N));
}
}
// This code is contributed by hrithikgarg03188
Javascript
输出:
50
时间复杂度: O(1)
辅助空间: O(1)