Dado un rango [L, R] , la tarea es imprimir todos los cuadrados perfectos del rango dado.
Ejemplos:
Entrada: L = 2, R = 24
Salida: 4 9 16
Entrada: L = 1, R = 100
Salida: 1 4 9 16 25 36 49 64 81 100
Enfoque ingenuo: comenzando de L a R, verifique si el elemento actual es un cuadrado perfecto o no. Si es así, imprímelo.
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 print all the perfect // squares from the given range void perfectSquares(float l, float r) { // For every element from the range for (int i = l; i <= r; i++) { // If current element is // a perfect square if (sqrt(i) == (int)sqrt(i)) cout << i << " "; } } // Driver code int main() { int l = 2, r = 24; perfectSquares(l, r); return 0; }
Java
//Java implementation of the approach import java.io.*; class GFG { // Function to print all the perfect // squares from the given range static void perfectSquares(int l, int r) { // For every element from the range for (int i = l; i <= r; i++) { // If current element is // a perfect square if (Math.sqrt(i) == (int)Math.sqrt(i)) System.out.print(i + " "); } } // Driver code public static void main (String[] args) { int l = 2, r = 24; perfectSquares(l, r); } } // This code is contributed by jit_t
Python3
# Python3 implementation of the approach # Function to print all the perfect # squares from the given range def perfectSquares(l, r): # For every element from the range for i in range(l, r + 1): # If current element is # a perfect square if (i**(.5) == int(i**(.5))): print(i, end=" ") # Driver code l = 2 r = 24 perfectSquares(l, r) # This code is contributed by mohit kumar 29
C#
// C# implementation of the approach using System; class GFG { // Function to print all the perfect // squares from the given range static void perfectSquares(int l, int r) { // For every element from the range for (int i = l; i <= r; i++) { // If current element is // a perfect square if (Math.Sqrt(i) == (int)Math.Sqrt(i)) Console.Write(i + " "); } } // Driver code public static void Main(String[] args) { int l = 2, r = 24; perfectSquares(l, r); } } // This code is contributed by 29AjayKumar
Javascript
<script> // js implementation of the approach // Function to print all the perfect // squares from the given range function perfectSquares(l, r){ //For every element from the range for (let i = l; i <= r; i++) { // If current element is // a perfect square if (Math.sqrt(i) == parseInt(Math.sqrt(i))) document.write(i + " "); } } // Driver code let l = 2; let r = 24; perfectSquares(l, r) // This code is contributed by sravan. </script>
4 9 16
Es solución con O(n). además, el uso del número de raíces cuadradas genera gastos de cálculo.
Enfoque eficiente: este método se basa en el hecho de que el primer cuadrado perfecto después del número L definitivamente será el cuadrado de ⌈sqrt(L)⌉ . En términos muy simples, la raíz cuadrada de L estará muy cerca del número cuya raíz cuadrada estamos tratando de encontrar. Por lo tanto, el número será pow(ceil(sqrt(L)), 2) .
El primer cuadrado perfecto es importante para este método. Ahora la respuesta original está oculta sobre este patrón, es decir, 0 1 4 9 16 25
la diferencia entre 0 y 1 es 1
la diferencia entre 1 y 4 es 3
la diferencia entre 4 y 9 es 5 y así sucesivamente…
lo que significa que la diferencia entre dos cuadrados perfectos es siempre un número impar.
Ahora, surge la pregunta de qué se debe sumar para obtener el siguiente número y la respuesta es (sqrt(X) * 2) + 1 donde X es el cuadrado perfecto ya conocido.
Deje que el cuadrado perfecto actual sea 4 , entonces el próximo cuadrado perfecto definitivamente será 4 + (sqrt (4) * 2 + 1) = 9 . Aquí, se suma el número 5 y el próximo número que se agregará será el 7 , luego el 9 y así sucesivamente… lo que hace una serie de números impares.
La suma es computacionalmente menos costosa que realizar la multiplicación o encontrar las raíces cuadradas de cada número.
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 print all the perfect // squares from the given range void perfectSquares(float l, float r) { // Getting the very first number int number = ceil(sqrt(l)); // First number's square int n2 = number * number; // Next number is at the difference of number = (number * 2) + 1; // While the perfect squares // are from the range while ((n2 >= l && n2 <= r)) { // Print the perfect square cout << n2 << " "; // Get the next perfect square n2 = n2 + number; // Next odd number to be added number += 2; } } // Driver code int main() { int l = 2, r = 24; perfectSquares(l, r); return 0; }
Java
// Java implementation of the approach class GFG { // Function to print all the perfect // squares from the given range static void perfectSquares(float l, float r) { // Getting the very first number int number = (int) Math.ceil(Math.sqrt(l)); // First number's square int n2 = number * number; // Next number is at the difference of number = (number * 2) + 1; // While the perfect squares // are from the range while ((n2 >= l && n2 <= r)) { // Print the perfect square System.out.print(n2 + " "); // Get the next perfect square n2 = n2 + number; // Next odd number to be added number += 2; } } // Driver code public static void main(String[] args) { int l = 2, r = 24; perfectSquares(l, r); } } // This code is contributed by 29AjayKumar
Python3
# Python3 implementation of the approach from math import ceil, sqrt # Function to print all the perfect # squares from the given range def perfectSquares(l, r) : # Getting the very first number number = ceil(sqrt(l)); # First number's square n2 = number * number; # Next number is at the difference of number = (number * 2) + 1; # While the perfect squares # are from the range while ((n2 >= l and n2 <= r)) : # Print the perfect square print(n2, end= " "); # Get the next perfect square n2 = n2 + number; # Next odd number to be added number += 2; # Driver code if __name__ == "__main__" : l = 2; r = 24; perfectSquares(l, r); # This code is contributed by AnkitRai01
C#
// C# implementation of the approach using System; class GFG { // Function to print all the perfect // squares from the given range static void perfectSquares(float l, float r) { // Getting the very first number int number = (int) Math.Ceiling(Math.Sqrt(l)); // First number's square int n2 = number * number; // Next number is at the difference of number = (number * 2) + 1; // While the perfect squares // are from the range while ((n2 >= l && n2 <= r)) { // Print the perfect square Console.Write(n2 + " "); // Get the next perfect square n2 = n2 + number; // Next odd number to be added number += 2; } } // Driver code public static void Main(String[] args) { int l = 2, r = 24; perfectSquares(l, r); } } // This code is contributed by Rajput Ji
Javascript
<script> // Javascript implementation of the approach // Function to print all the perfect // squares from the given range function perfectSquares(l, r) { // Getting the very first number let number = Math.ceil(Math.sqrt(l)); // First number's square let n2 = number * number; // Next number is at the difference of number = (number * 2) + 1; // While the perfect squares // are from the range while ((n2 >= l && n2 <= r)) { // Print the perfect square document.write(n2 + " "); // Get the next perfect square n2 = n2 + number; // Next odd number to be added number += 2; } } // Driver code let l = 2, r = 24; perfectSquares(l, r); // This code is contributed by subhammahato348 </script>
4 9 16
Publicación traducida automáticamente
Artículo escrito por Abhimanyu_kumar y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA