Dado un número entero N , la tarea es encontrar la cuenta de 0 en un hexágono de N niveles .
Ejemplos:
Entrada: N = 2
Salida: 7
Entrada: N = 3
Salida: 19
Planteamiento: Para los valores de N = 1, 2, 3,… se puede observar que se formará una serie como 1, 7, 19, 37, 61, 91, 127, 169,… . Es una serie de diferencias donde las diferencias están en AP como 6, 12, 18, … .
Por lo tanto el término N de será 1 + {6 + 12 + 18 +…..(n – 1) términos}
= 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)
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> 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
<script> // Javascript implementation of the approach // Function to return the count of // 0s in an n-level hexagon function count(n) { return 3 * n * (n - 1) + 1; } // Driver code var n = 3; document.write(count(n)); // This code is contributed by rutvik_56. </script>
Producción:
19
Complejidad de tiempo: O(1)
Espacio Auxiliar: O(1)