📜  N级六角形中的0计数

📅  最后修改于: 2021-04-27 22:59:21             🧑  作者: Mango

给定整数N ,任务是找到N级六边形中的0计数。

例子:

方法:对于N = 1,2,3,…的值,可以观察到一系列将形成为1,7,19,37,61,91,127,169,… 。这是一个差异序列,其中AP中的差异为6、12、18 ,…。
因此,第N项将是1 + {6 + 12 + 18 +…..(n – 1)个项}
= 1 +(n – 1)*(2 * 6 +(n – 1 – 1)* 6)/ 2
= 1 +(n – 1)*(12 +(n – 2)* 6)/ 2
= 1 +(n – 1)*(12 + 6n – 12)/ 2
= 1 +(n – 1)*(6n)/ 2
= 1 +(n – 1)*(3n)
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the count of
// 0s in an n-level hexagon
int count(int n)
{
    return 3 * n * (n - 1) + 1;
}
 
// Driver code
int main()
{
    int n = 3;
 
    cout << count(n);
 
    return 0;
}


Java
// Java implementation of the above approach
class GFG
{
     
    // Function to return the count of
    // 0s in an n-level hexagon
    static int count(int n)
    {
        return 3 * n * (n - 1) + 1;
    }
     
    // Driver code
    public static void main(String args[])
    {
        int n = 3;
     
        System.out.println(count(n));
    }
}
 
// This code is contributed by AnkitRai01


Python3
# Python3 implementation of the approach
 
# Function to return the count of
# 0s in an n-level hexagon
def count(n):
    return 3 * n * (n - 1) + 1
 
# Driver code
n = 3
 
print(count(n))
 
# This code is contributed by Mohit Kumar


C#
// C# implementation of the approach
using System;
 
class GFG
{
     
// Function to return the count of
// 0s in an n-level hexagon
static int count(int n)
{
    return 3 * n * (n - 1) + 1;
}
 
// Driver code
static public void Main ()
{
    int n = 3;
     
    Console.Write(count(n));
}
}
 
// This code is contributed by ajit


Javascript


输出:
19