找到系列 0、2、6、12、20、30、42... 的第 N 项
给定一个正整数N ,任务是找到序列的第 N 项
0, 2, 6, 12, 20…till N terms
例子:
Input: N = 7
Output: 42
Input: N = 10
Output: 90
方法:
从给定的系列中,找到第 N项的公式-
1st term = 1 * (1 – 1) = 0
2nd term = 2 * (2 – 1) = 2
3rd term = 3 * (3 – 1) = 6
4th term = 4 * (4 – 1) = 12
.
.
Nth term = N * (N – 1)
给定系列的第 N项可以概括为-
TN = N * (N – 1)
插图:
Input: N = 7
Output: 42
Explanation:
TN = N * (N – 1)
= 7 * (7 – 1)
= 7 * 6
= 42
以下是上述方法的实现 -
C++
// C++ program to implement
// the above approach
#include
using namespace std;
// Function to return
// Nth term of the series
int nthTerm(int n)
{
return n * n - n;
}
// Driver code
int main()
{
// Value of N
int N = 7;
cout << nthTerm(N) << endl;
return 0;
}
C
// C program to implement
// the above approach
#include
// Function to return
// Nth term of the series
int nthTerm(int n)
{
return n * n - n;
}
// Driver code
int main()
{
// Value of N
int N = 7;
printf("%d", nthTerm(N));
return 0;
}
Java
// Java program to implement
// the above approach
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Value of N
int N = 7;
System.out.println(nthTerm(N));
}
// Function to return
// Nth term of the series
public static int nthTerm(int n)
{
return n * n - n;
}
}
Python3
# Python code for the above approach
# Function to return
# Nth term of the series
def nthTerm(n):
return n * n - n;
# Driver code
# Value of N
N = 7;
print(nthTerm(N));
# This code is contributed by Saurabh Jaiswal
C#
using System;
public class GFG
{
// Function to return
// Nth term of the series
public static int nthTerm(int n)
{
return n * n - n;
}
static public void Main()
{
// Code
// Value of N
int N = 7;
Console.Write(nthTerm(N));
}
}
// This code is contributed by Potta Lokesh
Javascript
输出
42
时间复杂度: O(1)
辅助空间: O(1)