给定该系列的前两个项分别为1和6,并且该系列的所有元素都比其前后的均值小2。任务是打印系列的第n个术语。
该系列的前几个术语是:
1, 6, 15, 28, 45, 66, 91, …
例子:
Input: N = 3
Output: 15
Input: N = 1
Output: 1
方法:给定的级数表示三角数列中的奇数位置数。由于可以通过(n *(n + 1)/ 2)轻松找到第n个三角数,因此为了找到奇数,我们可以将n替换为(2 * n)– 1,因为(2 * n)– 1将总是产生奇数,即给定序列的第n个数将是((2 * n)– 1)* n 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the nth term
// of the given series
int oddTriangularNumber(int N)
{
return (N * ((2 * N) - 1));
}
// Driver code
int main()
{
int N = 3;
cout << oddTriangularNumber(N);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the nth term
// of the given series
static int oddTriangularNumber(int N)
{
return (N * ((2 * N) - 1));
}
// Driver code
public static void main(String[] args)
{
int N = 3;
System.out.println(oddTriangularNumber(N));
}
}
// This code contributed by Rajput-Ji
Python3
# Python 3 implementation of the approach
# Function to return the nth term
# of the given series
def oddTriangularNumber(N):
return (N * ((2 * N) - 1))
# Driver code
if __name__ == '__main__':
N = 3
print(oddTriangularNumber(N))
# This code is contributed by
# Surendra_Gangwar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the nth term
// of the given series
static int oddTriangularNumber(int N)
{
return (N * ((2 * N) - 1));
}
// Driver code
public static void Main(String[] args)
{
int N = 3;
Console.WriteLine(oddTriangularNumber(N));
}
}
/* This code contributed by PrinciRaj1992 */
PHP
Javascript
输出:
15