📜  N级六角形中的彩色0数

📅  最后修改于: 2021-05-07 00:06:43             🧑  作者: Mango

给定整数N ,任务是在以下列方式对0进行着色时,在N级六边形中查找着色的0的计数:

例子:

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

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


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


Python3
# Python3 implementation of the approach
 
# Function to return the count of
# coloured 0s in an n-level hexagon
def count(n) :
 
    return n * (3 * n - 1) // 2;
 
# Driver code
if __name__ == "__main__" :
 
    n = 3;
 
    print(count(n));
 
# This code is contributed by AnkitRai01


C#
// C# implementation of the approach
using System;
     
class GFG
{
     
// Function to return the count of
// coloured 0s in an n-level hexagon
static int count(int n)
{
    return n * (3 * n - 1) / 2;
}
 
// Driver code
public static void Main(String[] args)
{
    int n = 3;
 
    Console.WriteLine(count(n));
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
12