给定整数n,任务是找到第n个六角形数。第n个六边形数字Hn是由正六边形的轮廓组成的点阵图案中不同点的数量,这些正六边形的轮廓在重叠六边形以共享一个顶点时最多可包含n个点。{Source:wiki}
Input: n = 2
Output: 6
Input: n = 5
Output: 45
Input: n = 7
Output: 91
通常,多边形数(三角形数,平方数等)是表示为以规则多边形的形状排列的点或小卵石的数字。前几个五边形数字是1、5、12等。
如果s是多边形中的边数,则第n个s角数P(s,n)的公式为
nth s-gonal number P(s, n) = (s - 2)n(n-1)/2 + n
If we put s = 6, we get
n'th Hexagonal number Hn = 2(n*n)-n
= n(2n - 1)
C
// C program for above approach
#include
#include
// Finding the nth Hexagonal Number
int hexagonalNum(int n)
{
return n*(2*n - 1);
}
// Driver program to test above function
int main()
{
int n = 10;
printf("10th Hexagonal Number is = %d",
hexagonalNum(n));
return 0;
}
Java
// Java program for above approach
class Hexagonal
{
int hexagonalNum(int n)
{
return n*(2*n - 1);
}
}
public class GeeksCode
{
public static void main(String[] args)
{
Hexagonal obj = new Hexagonal();
int n = 10;
System.out.printf("10th Hexagonal number is = "
+ obj.hexagonalNum(n));
}
}
Python
# Python program for finding Hexagonal numbers
def hexagonalNum( n ):
return n*(2*n - 1)
# Driver code
n = 10
print "10th Hexagonal Number is = ", hexagonalNum(n)
C#
// C# program for above approach
using System;
class GFG {
static int hexagonalNum(int n)
{
return n * (2 * n - 1);
}
public static void Main()
{
int n = 10;
Console.WriteLine("10th Hexagonal"
+ " number is = " + hexagonalNum(n));
}
}
// This code is contributed by vt_m.
PHP
Javascript
输出:
10th Hexagonal Number is = 190