Comprobar si un número es cuadrado perfecto sin encontrar la raíz cuadrada

Comprueba si un número es un cuadrado perfecto o no sin encontrar su raíz cuadrada. 

Ejemplos: 

Entrada: n = 36 
Salida:

Entrada: n = 12 
Salida: No 

Hemos discutido un método para verificar si un número es un cuadrado perfecto .

Método 1:
la idea es ejecutar un bucle desde i = 1 hasta floor(sqrt(n)) y luego comprobar si al elevarlo al cuadrado se obtiene n. 

A continuación se muestra la implementación:

C++

// C++ program to check if a number is perfect
// square without finding square root
#include <bits/stdc++.h>
using namespace std;
 
bool isPerfectSquare(int n)
{
    for (int i = 1; i * i <= n; i++) {
 
        // If (i * i = n)
        if ((n % i == 0) && (n / i == i)) {
            return true;
        }
    }
    return false;
}
 
// Driver code
int main()
{
    long long int n = 36;
    if (n == 0 || isPerfectSquare(n))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}

Java

// Java program to check if a number is perfect
// square without finding the square root
public class GfG {
 
    static boolean isPerfectSquare(int n)
    {
        for (int i = 1; i * i <= n; i++) {
 
            // If (i * i = n)
            if ((n % i == 0) && (n / i == i)) {
                return true;
            }
        }
        return false;
    }
 
    public static void main(String[] args)
    {
 
        int n = 36;
 
        if (n == 0 || isPerfectSquare(n))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed by Rituraj Jain

Python3

# Python3 program to check if a number is
# perfect square without finding square root
 
# from math import sqrt function
 
 
def isPerfectSquare(n) :
 
    i = 1
    while(i * i<= n):
         
        # If (i * i = n)
        if ((n % i == 0) and (n / i == i)):
            return True
             
        i = i + 1
    return False
 
# Driver code
if __name__ == "__main__" :
 
    n = 36
    if (isPerfectSquare(n)):
        print("Yes, it is a perfect square.")
    elif n == 0:
        print("Yes, it is a perfect square.")
    else :
        print("No, it is not a perfect square.")
 
    # This code is contributed by Ryuga

C#

// C# program to check if a number is perfect
// square without finding the square root
using System;
 
public class GfG {
 
    static bool isPerfectSquare(int n)
    {
        for (int i = 1; i * i <= n; i++) {
 
            // If (i * i = n)
            if ((n % i == 0) && (n / i == i)) {
                return true;
            }
        }
        return false;
    }
 
    public static void Main()
    {
 
        int n = 36;
 
        if (n == 0 || isPerfectSquare(n))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
/*This code is contributed by Rajput-Ji*/

PHP

<?php
// PHP program to check if a number is perfect
// square without finding square root
 
function isPerfectSquare($n)
{
    for ($i = 1; $i * $i <= $n; $i++) {
 
        // If (i * i = n)
        if (($n % $i == 0) && ($n / $i == $i)) {
            return true;
        }
    }
    return false;
}
     
// Driver code
$n = 36;
if ($n == 0 || isPerfectSquare($n))
    echo "Yes";    
else
    echo "No";
 
// This code is contributed
// by Akanksha Rai

Javascript

<script>
// JavaScript program to check if a number is perfect
// square without finding square root
 
function isPerfectSquare(n)
{
    for (let i = 1; i * i <= n; i++) {
 
        // If (i * i = n)
        if ((n % i == 0) && (Math.floor(n / i) == i)) {
            return true;
        }
    }
    return false;
}
 
// Driver code
 
    let n = 36;
    if (n == 0 || isPerfectSquare(n))
        document.write("Yes");
    else
        document.write("No");
 
 
 
 
// This code is contributed by Surbhi Tyagi.
</script>
Producción

Yes

Complejidad de tiempo: O(sqrt(N))
Espacio auxiliar: O(1)

Método 2:
La idea es utilizar la búsqueda binaria para encontrar un número en el rango de 1 a n cuyo cuadrado sea igual a n, de modo que en cada iteración el enunciado del problema se reduzca a la mitad [1 a n/2-1 O n/2 a n].

A continuación se muestra la implementación:

C++

// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
 
// Program to find if x is a
// perfect square.
bool isPerfectSquare(int x)
{
    long long left = 1, right = x;
 
    while (left <= right) {
        long long mid = (left + right) / 2;
 
        // Check if mid is perfect square
        if (mid * mid == x) {
            return true;
        }
 
        // Mid is small -> go right to increase mid
        if (mid * mid < x) {
            left = mid + 1;
        }
 
        // Mid is large -> to left to decrease mid
        else {
            right = mid - 1;
        }
    }
    return false;
}
 
// Driver Code
int main()
{
    int n = 2500;
 
    // Function Call
    if (n == 0 || isPerfectSquare(n))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}

Java

// Java program for above approach
class GFG
{
     
    // Program to find if x is a
    // perfect square.
    static boolean isPerfectSquare(int num)
    {
        long left = 1, right = num;
         
        while (left <= right)
        {
            long mid = (left + right) / 2;
           
            // Check if mid is perfect square
            if (mid * mid == num)
            {
                return true;
            }
            
            // Mid is small -> go right to increase mid
            if (mid * mid < num)
            {
                left = mid + 1;
            }
           
            // Mid is large -> to left to decrease mid
            else
            {
                right = mid - 1;
            }
        }
        return false;
    }
     
    // Driver code
    public static void main(String[] args)
    {
        int x = 2500;
         
        // Function Call
        if (x == 0 || isPerfectSquare(x))
            System.out.print("Yes");
        else
            System.out.print("No");
    }
}

Python3

# Python program for above approach
 
# Program to find if x is a
# perfect square.
def isPerfectSquare(x):
     
    left = 1
    right = x
     
    while (left <= right):
       
        mid = (left + right) >> 1
         
        # Check if mid is perfect square
        if ((mid * mid) == x):
            return True
         
        # Mid is small -> go right to increase mid
        if (mid * mid < x):
            left = mid + 1
           
        # Mid is large -> to left to decrease mid
        else:
            right = mid - 1
    return False
 
# Driver code
if __name__ == "__main__":
   
  x = 2500
   
  # Function Call
  if x == 0:
        print("Yes, it is a perfect square.")
  elif (isPerfectSquare(x)):
      print("Yes")
  else:
      print("No")

C#

// C# program for above approach
using System;
class GFG{
     
// Program to find if x is a
// perfect square.
static bool isPerfectSquare(int x)
{
  long left = 1, right = x;
 
  while (left <= right)
  {
    long mid = (left + right) / 2;
 
    // Check if mid is perfect
    // square
    if (mid * mid == x)
    {
      return true;
    }
 
    // Mid is small -> go right to
    // increase mid
    if (mid * mid < x)
    {
      left = mid + 1;
    }
 
    // Mid is large -> to left
    // to decrease mid
    else
    {
      right = mid - 1;
    }
  }
  return false;
}
      
// Driver code
public static void Main(string[] args)
{
  int n = 2500;
 
  // Function Call
  if (n == 0 || isPerfectSquare(n))
    Console.Write("Yes");
  else
    Console.Write("No");
}
}
 
// This code is contributed by Rutvik_56n == 0 ||

Javascript

<script>
 
// Javascript program for above approach
 
// Program to find if x is a
// perfect square.
function isPerfectSquare(x)
{ 
    let left = 1, right = x;
   
    while (left <= right)
    {
        let mid = parseInt((left + right) / 2);
        
        // Check if mid is perfect square
        if (mid * mid == x)
        {
            return true;
        }
         
        // Mid is small -> go right to increase mid
        if (mid * mid < x)
        {
            left = mid + 1;
        }
       
        // Mid is large -> to left to decrease mid
        else
        {
            right = mid - 1;
        }
    }
    return false;
}
 
// Driver Code
let x = 2500;
 
// Function Call
if (x == 0 || isPerfectSquare(x))
    document.write("Yes");
else
    document.write("Yes");
     
// This code is contributed by rishavmahato348
 
</script>
Producción

Yes

Complejidad de tiempo: O(log(N))
Espacio auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por mukul166 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *