Count of 0s in an N-level hexagon
Last Updated :
10 Mar, 2022
Given an integer N, the task is to find the count of 0s in an N-level hexagon.
Examples:
Input: N = 2
Output: 7
Input: N = 3
Output: 19
Approach: For the values of N = 1, 2, 3, … it can be observed that a series will be formed as 1, 7, 19, 37, 61, 91, 127, 169, …. It’s a difference series where differences are in AP as 6, 12, 18, ….
Therefore the Nth term of will be 1 + {6 + 12 + 18 +…..(n – 1) terms}
= 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)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int count( int n)
{
return 3 * n * (n - 1) + 1;
}
int main()
{
int n = 3;
cout << count(n);
return 0;
}
|
Java
class GFG
{
static int count( int n)
{
return 3 * n * (n - 1 ) + 1 ;
}
public static void main(String args[])
{
int n = 3 ;
System.out.println(count(n));
}
}
|
Python3
def count(n):
return 3 * n * (n - 1 ) + 1
n = 3
print (count(n))
|
C#
using System;
class GFG
{
static int count( int n)
{
return 3 * n * (n - 1) + 1;
}
static public void Main ()
{
int n = 3;
Console.Write(count(n));
}
}
|
Javascript
<script>
function count(n)
{
return 3 * n * (n - 1) + 1;
}
var n = 3;
document.write(count(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...