Dado un número entero N , la tarea es encontrar el número de celdas en la figura de orden N del tipo dado:
Ejemplos:
Entrada: N = 2
Salida: 5
Entrada: N = 3
Salida: 13
Planteamiento: Se puede observar que para los valores de N = 1, 2, 3,… se formará una serie como 1, 5, 13, 25, 41, 61, 85, 113, 145, 181, … cuyo Nth el término será N 2 + (N – 1) 2 .
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 number // of cells in the nth order // figure of the given type int cntCells(int n) { int cells = pow(n, 2) + pow(n - 1, 2); return cells; } // Driver code int main() { int n = 3; cout << cntCells(n); return 0; }
Java
// Java implementation of the approach class GFG { // Function to return the number // of cells in the nth order // figure of the given type static int cntCells(int n) { int cells = (int)Math.pow(n, 2) + (int)Math.pow(n - 1, 2); return cells; } // Driver code public static void main(String[] args) { int n = 3; System.out.println(cntCells(n)); } } // This code is contributed by Code_Mech
Python3
# Python3 implementation of the approach # Function to return the number # of cells in the nth order # figure of the given type def cntCells(n) : cells = pow(n, 2) + pow(n - 1, 2); return cells; # Driver code if __name__ == "__main__" : n = 3; print(cntCells(n)); # This code is contributed by AnkitRai01
C#
// C# implementation of the approach using System; class GFG { // Function to return the number // of cells in the nth order // figure of the given type static int cntCells(int n) { int cells = (int)Math.Pow(n, 2) + (int)Math.Pow(n - 1, 2); return cells; } // Driver code public static void Main(String[] args) { int n = 3; Console.WriteLine(cntCells(n)); } } // This code is contributed by 29AjayKumar
Javascript
<script> // Javascript implementation of the approach // Function to return the number // of cells in the nth order // figure of the given type function cntCells(n) { var cells = Math.pow(n, 2) + Math.pow(n - 1, 2); return cells; } // Driver code var n = 3; document.write(cntCells(n)); </script>
Producción:
13
Complejidad de tiempo: O(1)
Espacio auxiliar: O(1), ya que no se requiere espacio adicional