给定数字N ,任务是编写一个程序来查找中心多边形数系列的第N个项:
1, 1, 3, 7, 13, 21, 31, 43, 57…..
例子:
Input: N = 0
Output: 1
Input: N = 3
Output: 7
方法:第N个术语可以形式化为:
Series = 1, 3, 7, 13, 21, 31, 43, 57……
Difference = 3-1, 7-3, 13-7, 21-13…………….
Difference = 2, 4, 6, 8……which is a AP
So nth term of given series
= 1 + (2, 4, 6, 8 …… (n-1)terms)
= 1 + (n-1)/2*(2*2+(n-1-1)*2)
= 1 + (n-1)/2*(4+2n-4)
= 1 + (n-1)*n
= n^2 – n + 1
因此,该系列的第N个项为
下面是上述方法的实现:
C++
// C++ program to find N-th term
// in the series
#include
#include
using namespace std;
// Function to find N-th term
// in the series
void findNthTerm(int n)
{
cout << n * n - n + 1 << endl;
}
// Driver code
int main()
{
int N = 4;
findNthTerm(N);
return 0;
}
Java
// Java program to find N-th term
// in the series
class GFG{
// Function to find N-th term
// in the series
static void findNthTerm(int n)
{
System.out.println(n * n - n + 1);
}
// Driver code
public static void main(String[] args)
{
int N = 4;
findNthTerm(N);
}
}
// This code is contributed by Ritik Bansal
Python3
# Python3 program to find N-th term
# in the series
# Function to find N-th term
# in the series
def findNthTerm(n):
print(n * n - n + 1)
# Driver code
N = 4
# Function Call
findNthTerm(N)
# This code is contributed by Vishal Maurya
C#
// C# program to find N-th term
// in the series
using System;
class GFG{
// Function to find N-th term
// in the series
static void findNthTerm(int n)
{
Console.Write(n * n - n + 1);
}
// Driver code
public static void Main()
{
int N = 4;
findNthTerm(N);
}
}
// This code is contributed by nidhi_biet
Javascript
输出:
13