📜  中心三角数

📅  最后修改于: 2021-04-24 22:18:18             🧑  作者: Mango

给定整数n,找到第n个中心三角数。
中心三角数是一个中心多边形数,代表一个三角形,中间带有一个点,而在相邻的三角形层中,所有其他围绕该中心的点[Source:Wiki]
绘画作品:

居中Trigunal数字pic

前几个居中的三角数系列是:
1,4,10,19,31,46,64,85,109,136,166,199,235,274,316,361,409,460 ………..
例子:

Input : n = 1
Output : 4
Explanation :
A dot in the centre and 3 dots forming the
triangle outside it, thus 4.

Input : n = 6 
Output : 64

Input : n = 10
Output : 166

方法
中心三角数的第n个项由下式给出:

CT_{n}=(3n^2+3n+2)/2

上述方法的基本实现:

C++
// CPP Program to find the
// nth Centered Trigunal number
#include
using namespace std;
 
// function for Centered
// Trigunal number
int Centered_Trigunal_num(int n)
{
    // formula for find Centered
    // Trigunal number nth term
    return (3 * n * n + 3 * n + 2) / 2;
}
 
// Driver Code
int main()
{
    // For 3rd Centered Trigunal number
    int n = 3;
    cout << Centered_Trigunal_num(n) << endl;
 
    // For 12th Centered Trigunal number
    n = 12;
    cout << Centered_Trigunal_num(n) << endl;
 
    return 0;
}


Java
// Java Program to find
// the nth Centered
// Triangular number
import java.io.*;
 
class GFG
{
     
// function for Centered
// Trigunal number
static int Centered_Trigunal_num(int n)
{
    // formula for find Centered
    // Trigunal number nth term
    return (3 * n * n +
            3 * n + 2) / 2;
}
 
// Driver Code
public static void main (String[] args)
{
 
// For 3rd Centered
// Trigunal number
int n = 3;
System.out.println(Centered_Trigunal_num(n));
 
// For 12th Centered
// Trigunal number
n = 12;
System.out.println(Centered_Trigunal_num(n));
}
}
 
// This code is contributed by ajit


Python3
# Program to find nth
# Centered Trigunal number
 
def Centered_Trigunal_num(n) :
     
    # Formula to calculate nth
    # Centered Trigunal number
    return (3 * n * n +
            3 * n + 2) // 2
 
# Driver Code
if __name__ == '__main__' :
 
    # For 3rd Centered
    # Trigunal number    
    n = 3
    print(Centered_Trigunal_num(n))
     
    # For 12th Centered
    # Trigunal number
    n = 12
    print(Centered_Trigunal_num(n))
                 
                 
# This code is contributed
# by akt_mit


C#
// C# Program to find
// the nth Centered
// Triangular number
using System;
 
class GFG
{
 
// function for Centered
// Trigunal number
static int Centered_Trigunal_num(int n)
{
    // formula for find Centered
    // Trigunal number nth term
    return (3 * n * n +
            3 * n + 2) / 2;
}
 
// Driver Code
static public void Main ()
{
 
// For 3rd Centered
// Trigunal number
int n = 3;
Console.WriteLine(Centered_Trigunal_num(n));
 
// For 12th Centered
// Trigunal number
n = 12;
Console.WriteLine(Centered_Trigunal_num(n));
}
}
 
// This code is contributed by akt_mit


PHP


Javascript


输出 :

19
235