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