Square root of a number without using sqrt() function

Given a number N, the task is to find the square root of N without using sqrt() function.

Examples:

Input: N = 25
Output: 5

Input: N = 3
Output: 1.73205

Input: N = 2.5
Output: 1.58114



Approach:

  • Start iterating from i = 1. If i * i = n, then print i as n is a perfect square whose square root is i.
  • Else find the smallest i for which i * i is strictly greater than n.
  • Now we know square root of n lies in the interval i – 1 and i and we can use Binary Search algorithm to find the square root.
  • Find mid of i – 1 and i and compare mid * mid with n, with precision upto 5 decimal places.
    1. If mid * mid = n then return mid.
    2. If mid * mid < n then recur for the second half.
    3. If mid * mid > n then recur for the first half.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output:

1.73205

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :


5


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.