📜  七边形数

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

给定一个数 n,任务是找到第 N 个七边形数。 Heptagonal 数代表七边形,属于比喻数。七边形有七个角、七个顶点和七边多边形。
例子 :

七边形

很少有七边形数是:
1、7、18、34、55、81、112、148、189、235…………
计算第 N 个七边形数的公式:

\begin{math}  Hep_{n}=((5*n*n)-3*n)/2 \end{math}

C++
// C++ program to find the
// nth Heptagonal number
#include 
using namespace std;
 
// Function to return Nth Heptagonal
// number
int heptagonalNumber(int n)
{
    return ((5 * n * n) - (3 * n)) / 2;
}
 
// Drivers Code
int main()
{
 
    int n = 2;
    cout << heptagonalNumber(n) << endl;
    n = 15;
    cout << heptagonalNumber(n) << endl;
 
    return 0;
}


Java
// Java program to find the
// nth Heptagonal number
import java.io.*;
 
class GFG
{
// Function to return
// Nth Heptagonal number
static int heptagonalNumber(int n)
{
    return ((5 * n * n) - (3 * n)) / 2;
}
 
// Driver Code
public static void main (String[] args)
{
    int n = 2;
    System.out.println(heptagonalNumber(n));
    n = 15;
    System.out.println(heptagonalNumber(n));
}
}
 
// This code is contributed by anuj_67.


Python3
# Program to find nth
# Heptagonal number
 
# Function to find
# nth Heptagonal number
def heptagonalNumber(n) :
     
    # Formula to calculate
    # nth Heptagonal number
    return ((5 * n * n) -
            (3 * n)) // 2
 
# Driver Code
if __name__ == '__main__' :
    n = 2
    print(heptagonalNumber(n))
    n = 15
    print(heptagonalNumber(n))
                 
# This code is contributed
# by ajit


C#
// C# program to find the
// nth Heptagonal number
using System;
 
class GFG
{
// Function to return
// Nth Heptagonal number
static int heptagonalNumber(int n)
{
    return ((5 * n * n) -
            (3 * n)) / 2;
}
 
// Driver Code
public static void Main ()
{
    int n = 2;
    Console.WriteLine(heptagonalNumber(n));
    n = 15;
    Console.WriteLine(heptagonalNumber(n));
}
}
 
// This code is contributed by anuj_67.


PHP


Javascript


输出 :
7
540

时间复杂度: O(1)
辅助空间: O(1)

参考: https : //en.wikipedia.org/wiki/Heptagonal_number

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