Open In App

Number of coloured 0’s in an N-level hexagon

Last Updated : 10 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer N, the task is to find the count of coloured 0s in an N-level hexagon when the 0s are coloured in the following way: 
 

Examples: 
 

Input: N = 2 
Output: 5
Input: N = 3 
Output: 12 
 

 

Approach: For the values of N = 1, 2, 3, … it can be observed that a series will be formed as 1, 5, 12, 22, 35, …. It’s a difference series where differences are in AP as 4, 7, 10, 13, …
Therefore the Nth term of will be 1 + {4 + 7 + 10 +13 +…..(n – 1) terms} 
= 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
Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
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




<script>
 
// Javascript implementation of the approach
 
// Function to return the count of
// coloured 0s in an n-level hexagon
function count(n)
{
    return parseInt(n * (3 * n - 1) / 2);
}
 
// Driver code
var n = 3;
document.write(count(n));
 
</script>


Output: 

12

 

Time Complexity: O(1)

Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads