Find square root of number upto given precision using binary search

Given a positive number n and precision p, find the square root of number upto p decimal places using binary search.
Note : Prerequisite : Binary search
Examples:

Input : number = 50, precision = 3
Output : 7.071

Input : number = 10, precision = 4
Output : 3.1622

We have discussed how to compute integral value of square root in Square Root using Binary Search



Approach :
1) As the square root of number lies in range 0 <= squareRoot <= number, therefore, initialize start and end as : start = 0, end = number.
2) Compare the square of mid integer with the given number. If it is equal to the number, then we found our integral part, else look for the same in left or right side depending upon the scenario.
3) Once we are done with finding the integral part, start computing the fractional part.
4) Initialize the increment variable by 0.1 and iteratively compute the fractional part upto p places. For each iteration, increment changes to 1/10th of it’s previous value.
5) Finally return the answer computed.

Below is the implementation of above approach :

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find
// square root of given number
// upto given precision using
// binary search.
#include <bits/stdc++.h>
using namespace std;
  
// Function to find square root
// of given number upto given
// precision
float squareRoot(int number, int precision)
{
    int start = 0, end = number;
    int mid;
  
    // variable to store the answer
    float ans;
  
    // for computing integral part
    // of square root of number
    while (start <= end) {
        mid = (start + end) / 2;
        if (mid * mid == number) {
            ans = mid;
            break;
        }
  
        // incrementing start if integral
        // part lies on right side of the mid
        if (mid * mid < number) {
            start = mid + 1;
            ans = mid;
        }
  
        // decrementing end if integral part
        // lies on the left side of the mid
        else {
            end = mid - 1;
        }
    }
  
    // For computing the fractional part
    // of square root upto given precision
    float increment = 0.1;
    for (int i = 0; i < precision; i++) {
        while (ans * ans <= number) {
            ans += increment;
        }
  
        // loop terminates when ans * ans > number
        ans = ans - increment;
        increment = increment / 10;
    }
    return ans;
}
  
// Driver code
int main()
{
    // Function calling
    cout << squareRoot(50, 3) << endl;
  
    // Function calling
    cout << squareRoot(10, 4) << endl;
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to find
// square root of given number
// upto given precision using
// binary search.
import java.io.*;
  
class GFG {
      
    // Function to find square root
    // of given number upto given
    // precision
    static float squareRoot(int number, int precision)
    {
        int start = 0, end = number;
        int mid;
  
        // variable to store the answer
        double ans = 0.0;
  
        // for computing integral part
        // of square root of number
        while (start <= end) 
        {
            mid = (start + end) / 2;
              
            if (mid * mid == number) 
            {
                ans = mid;
                break;
            }
  
            // incrementing start if integral
            // part lies on right side of the mid
            if (mid * mid < number) {
                start = mid + 1;
                ans = mid;
            }
  
            // decrementing end if integral part
            // lies on the left side of the mid
            else {
                end = mid - 1;
            }
        }
  
        // For computing the fractional part
        // of square root upto given precision
        double increment = 0.1;
        for (int i = 0; i < precision; i++) {
            while (ans * ans <= number) {
                ans += increment;
            }
  
            // loop terminates when ans * ans > number
            ans = ans - increment;
            increment = increment / 10;
        }
        return (float)ans;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        // Function calling
        System.out.println(squareRoot(50, 3));
  
        // Function calling
        System.out.println(squareRoot(10, 4));
    }
}
  
// This code is contributed by vt_m.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to find
# square root of given number
# upto given precision using
# binary search.
  
# Function to find square root of
# given number upto given precision
def squareRoot(number, precision):
  
    start = 0
    end = number
  
    # For computing integral part
    # of square root of number
    while (start <= end) :
        mid = int((start + end) / 2)
          
        if (mid * mid == number) :
            ans = mid
            break
          
        # incrementing start if integral
        # part lies on right side of the mid
        if (mid * mid < number) :
            start = mid + 1
            ans = mid
          
        # decrementing end if integral part
        # lies on the left side of the mid
        else :
            end = mid - 1
          
    # For computing the fractional part
    # of square root upto given precision
    increment = 0.1
    for i in range(0, precision): 
        while (ans * ans <= number):
            ans += increment
          
        # loop terminates when ans * ans > number
        ans = ans - increment
        increment = increment / 10
      
    return ans
  
# Driver code
print(round(squareRoot(50, 3), 4))
print(round(squareRoot(10, 4), 4))
      
# This code is contributed by Smitha Dinesh Semwal. 

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to find
// square root of given number
// upto given precision using
// binary search.
using System;
  
class GFG {
      
    static int mod = 1000000007;
      
    // Finding number of possible number with
    // n digits excluding a particular digit
    static int digitNumber(long n) {
      
        // Checking if number of digits is zero
        if (n == 0)
            return 1;
      
        // Checking if number of digits is one
        if (n == 1)
            return 9;
      
        // Checking if number of digits is odd
        if (n % 2 != 0) {
      
            // Calling digitNumber function
            // with (digit-1)/2 digits
            int temp = digitNumber((n - 1) / 2) % mod;
              
            return (9 * (temp * temp) % mod) % mod;
        
        else {
      
            // Calling digitNumber function
            // with n/2 digits
            int temp = digitNumber(n / 2) % mod;
              
            return (temp * temp) % mod;
        }
    }
      
    static int countExcluding(int n, int d) {
          
        // Calling digitNumber function
        // Checking if excluding digit is
        // zero or non-zero
        if (d == 0)
            return (9 * digitNumber(n - 1)) % mod;
        else
            return (8 * digitNumber(n - 1)) % mod;
    }
      
    // Driver function to run above program
    public static void Main() {
          
        // Initializing variables
        int d = 9;
        int n = 3;
          
        Console.WriteLine(countExcluding(n, d));
    }
}
  
// This code is contributed by vt_m.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP implementation to find
// square root of given number
// upto given precision using
// binary search.
  
// Function to find square root
// of given number upto given
// precision
function squareRoot($number, $precision)
{
    $start=0; 
    $end=$number;
    $mid;
  
    // variable to store
    // the answer
    $ans;
  
    // for computing integral part
    // of square root of number
    while ($start <= $end)
    {
        $mid = ($start + $end) / 2;
        if ($mid * $mid == $number
        {
            $ans = $mid;
            break;
        }
  
        // incrementing start if integral
        // part lies on right side of the mid
        if ($mid * $mid < $number)
        {
            $start = $mid + 1;
            $ans = $mid;
        }
  
        // decrementing end if integral part
        // lies on the left side of the mid
        else
        {
            $end = $mid - 1;
        }
    }
  
    // For computing the fractional part
    // of square root upto given precision
    $increment = 0.1;
    for ($i = 0; $i < $precision; $i++)
    {
        while ($ans * $ans <= $number
        {
            $ans += $increment;
        }
  
        // loop terminates when
        // ans * ans > number
        $ans = $ans - $increment;
        $increment = $increment / 10;
    }
    return $ans;
}
  
    // Driver code
    // Function calling
    echo squareRoot(50, 3),"\n";
  
    // Function calling
    echo squareRoot(10, 4),"\n";
  
// This code is contributed by ajit.
?>

chevron_right



Output :

7.071
3.1622

Time Complexity : The time required to compute the integral part is O(log(number)) and constant i.e, = precision for computing the fractional part. Therefore, overall time complexity is O(log(number) + precision) which is approximately equal to O(log(number)).



My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

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.



Improved By : jit_t