📜  第 n 个五边形数

📅  最后修改于: 2021-10-23 08:13:43             🧑  作者: Mango

给定一个整数 n,找出第 n 个五边形数。前三个五边形数字是 1、5 和 12(请参见下图)。
第 n 个五边形数 P n是由规则五边形的轮廓组成的点图案中不同点的数量,当五边形重叠时,边最多为 n 个点,因此它们共享一个顶点 [来源 Wiki]
例子 :

Input: n = 1
Output: 1

Input: n = 2
Output: 5

Input: n = 3
Output: 12

通常,多边形数(三角形数、正方形数等)是表示为以正多边形形状排列的点或卵石的数。前几个五边形数字是: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 = 5, we get

n'th Pentagonal number Pn = 3*n*(n-1)/2 + n

例子:

五角数

五角数

下面是上述思想在不同编程语言中的实现。

C++
// C++ program for above approach
#include
using namespace std;
 
// Finding the nth pentagonal number
int pentagonalNum(int n)
{
    return (3 * n * n - n) / 2;
}
 
// Driver code
int main()
{
    int n = 10;
     
    cout << "10th Pentagonal Number is = "
         << pentagonalNum(n);
 
    return 0;
}
 
// This code is contributed by Code_Mech


C
// C program for above approach
#include 
#include 
 
// Finding the nth Pentagonal Number
int pentagonalNum(int n)
{
    return (3*n*n - n)/2;
}
 
// Driver program to test above function
int main()
{
    int n = 10;
    printf("10th Pentagonal Number is = %d \n \n",
                             pentagonalNum(n));
 
    return 0;
}


Java
// Java program for above approach
class Pentagonal
{
    int pentagonalNum(int n)
    {
        return (3*n*n - n)/2;
    }
}
 
public class GeeksCode
{
    public static void main(String[] args)
    {
        Pentagonal obj = new Pentagonal();
        int n = 10;   
        System.out.printf("10th petagonal number is = "
                          + obj.pentagonalNum(n));
    }
}


Python
# Python program for finding pentagonal numbers
def pentagonalNum( n ):
    return (3*n*n - n)/2
#Script Begins
 
n = 10
print "10th Pentagonal Number is = ", pentagonalNum(n)
  
#Scripts Ends


C#
// C# program for above approach
using System;
 
class GFG {
     
    static int pentagonalNum(int n)
    {
        return (3 * n * n - n) / 2;
    }
 
    public static void Main()
    {
        int n = 10;
         
        Console.WriteLine("10th petagonal"
        + " number is = " + pentagonalNum(n));
    }
}
 
// This code is contributed by vt_m.


PHP


Javascript


输出 :

10th Pentagonal Number is = 145

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程