Raíz cuadrada de un número sin usar la función sqrt()

Dado un número N , la tarea es encontrar la raíz cuadrada de N sin usar la función sqrt() .

Ejemplos: 

Entrada: N = 25 
Salida: 5

Entrada: N = 3 
Salida: 1.73205

Entrada: N = 2,5 
Salida: 1,58114 
 

Acercarse:  

  • Comience iterando desde i = 1. Si i * i = n , imprima i como n es un cuadrado perfecto cuya raíz cuadrada es i .
  • Si no, encuentre el i más pequeño para el cual i * i es estrictamente mayor que n .
  • Ahora sabemos que la raíz cuadrada de n se encuentra en el intervalo i – 1 e i y podemos usar el algoritmo de búsqueda binaria para encontrar la raíz cuadrada.
  • Encuentre mid de i – 1 e i y compare mid * mid con n , con una precisión de hasta 5 decimales. 
    1. Si mid * mid = n , devuelve mid .
    2. Si mid * mid < n entonces se repite para la segunda mitad.
    3. Si mid * mid > n entonces se repite para la primera mitad.

A continuación se muestra la implementación del enfoque anterior:  

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Recursive function that returns square root
// of a number with precision upto 5 decimal places
double Square(double n, double i, double j)
{
    double mid = (i + j) / 2;
    double mul = mid * mid;
 
    // If mid itself is the square root,
    // return mid
    if ((mul == n) || (abs(mul - n) < 0.00001))
        return mid;
 
    // If mul is less than n, recur second half
    else if (mul < n)
        return Square(n, mid, j);
 
    // Else recur first half
    else
        return Square(n, i, mid);
}
 
// Function to find the square root of n
void findSqrt(double n)
{
    double i = 1;
 
    // While the square root is not found
    bool found = false;
    while (!found) {
 
        // If n is a perfect square
        if (i * i == n) {
            cout << fixed << setprecision(0) << i;
            found = true;
        }
        else if (i * i > n) {
 
            // Square root will lie in the
            // interval i-1 and i
            double res = Square(n, i - 1, i);
            cout << fixed << setprecision(5) << res;
            found = true;
        }
        i++;
    }
}
 
// Driver code
int main()
{
    double n = 3;
 
    findSqrt(n);
 
    return 0;
}

Java

// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
// Recursive function that returns
// square root of a number with
// precision upto 5 decimal places
static double Square(double n,
                     double i, double j)
{
    double mid = (i + j) / 2;
    double mul = mid * mid;
 
    // If mid itself is the square root,
    // return mid
    if ((mul == n) ||  
        (Math.abs(mul - n) < 0.00001))
        return mid;
 
    // If mul is less than n,
    // recur second half
    else if (mul < n)
        return Square(n, mid, j);
 
    // Else recur first half
    else
        return Square(n, i, mid);
}
 
// Function to find the square root of n
static void findSqrt(double n)
{
    double i = 1;
 
    // While the square root is not found
    boolean found = false;
    while (!found)
    {
 
        // If n is a perfect square
        if (i * i == n)
        {
            System.out.println(i);
            found = true;
        }
         
        else if (i * i > n)
        {
 
            // Square root will lie in the
            // interval i-1 and i
            double res = Square(n, i - 1, i);
            System.out.printf("%.5f", res);
            found = true;
        }
        i++;
    }
}
 
// Driver code
public static void main(String[] args)
{
    double n = 3;
 
    findSqrt(n);
}
}
 
// This code is contributed by PrinciRaj1992

Python3

# Python3 implementation of the approach
import math
 
# Recursive function that returns square root
# of a number with precision upto 5 decimal places
def Square(n, i, j):
 
    mid = (i + j) / 2;
    mul = mid * mid;
 
    # If mid itself is the square root,
    # return mid
    if ((mul == n) or (abs(mul - n) < 0.00001)):
        return mid;
 
    # If mul is less than n, recur second half
    elif (mul < n):
        return Square(n, mid, j);
 
    # Else recur first half
    else:
        return Square(n, i, mid);
 
# Function to find the square root of n
def findSqrt(n):
    i = 1;
 
    # While the square root is not found
    found = False;
    while (found == False):
 
        # If n is a perfect square
        if (i * i == n):
            print(i);
            found = True;
         
        elif (i * i > n):
 
            # Square root will lie in the
            # interval i-1 and i
            res = Square(n, i - 1, i);
            print ("{0:.5f}".format(res))
            found = True
        i += 1;
 
# Driver code
if __name__ == '__main__':
    n = 3;
 
    findSqrt(n);
 
# This code is contributed by 29AjayKumar

C#

// C# implementation of the approach
using System;
     
class GFG
{
 
// Recursive function that returns
// square root of a number with
// precision upto 5 decimal places
static double Square(double n,
                     double i, double j)
{
    double mid = (i + j) / 2;
    double mul = mid * mid;
 
    // If mid itself is the square root,
    // return mid
    if ((mul == n) ||
        (Math.Abs(mul - n) < 0.00001))
        return mid;
 
    // If mul is less than n,
    // recur second half
    else if (mul < n)
        return Square(n, mid, j);
 
    // Else recur first half
    else
        return Square(n, i, mid);
}
 
// Function to find the square root of n
static void findSqrt(double n)
{
    double i = 1;
 
    // While the square root is not found
    Boolean found = false;
    while (!found)
    {
 
        // If n is a perfect square
        if (i * i == n)
        {
            Console.WriteLine(i);
            found = true;
        }
         
        else if (i * i > n)
        {
 
            // Square root will lie in the
            // interval i-1 and i
            double res = Square(n, i - 1, i);
            Console.Write("{0:F5}", res);
            found = true;
        }
        i++;
    }
}
 
// Driver code
public static void Main(String[] args)
{
    double n = 3;
 
    findSqrt(n);
}
}
 
// This code is contributed by Princi Singh

Javascript

<script>
 
// Javascript implementation of the approach
 
// Recursive function that returns
// square root of a number with
// precision upto 5 decimal places
function Square(n, i, j)
{
    var mid = ((i + j) / 2);
    var mul = mid * mid;
 
    // If mid itself is the square root,
    // return mid
    if ((mul == n) || (Math.abs(mul - n) < 0.00001))
        return mid;
 
    // If mul is less than n,
    // recur second half
    else if (mul < n)
        return Square(n, mid, j);
 
    // Else recur first half
    else
        return Square(n, i, mid);
}
 
// Function to find the square root of n
function findSqrt(n)
{
    var i = 1;
 
    // While the square root is not found
    var found = false;
    while (!found)
    {
         
        // If n is a perfect square
        if (i * i == n)
        {
            document.write(i);
            found = true;
        }
 
        else if (i * i > n)
        {
             
            // Square root will lie in the
            // interval i-1 and i
            var res = Square(n, i - 1, i);
            document.write(res.toFixed(5));
            found = true;
        }
        i++;
    }
}
 
// Driver code
var n = 3;
 
findSqrt(n);
 
// This code is contributed by todaysgaurav
 
</script>
Producción: 

1.73205

 

Publicación traducida automáticamente

Artículo escrito por SnehanjanChatterjee 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 *