📜  第n个五角数

📅  最后修改于: 2021-05-04 15:57:55             🧑  作者: 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