Skip to content
Related Articles
Find square root of number upto given precision using binary search
• Difficulty Level : Medium
• Last Updated : 24 Jun, 2021

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 the 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 the mid integer with the given number. If it is equal to the number,  the square root is found. Else look for the same in the left or right side depending upon the scenario.
3) Once we are done with finding an integral part, start computing the fractional part.
4) Initialize the increment variable by 0.1 and iteratively compute the fractional part up to P places. For each iteration, the increment changes to 1/10th of its previous value.
5) Finally return the answer computed.
Below is the implementation of above approach :

## C++

 `// C++ implementation to find``// square root of given number``// upto given precision using``// binary search.``#include ``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;``}`

## Java

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

## Python3

 `# 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, ans ``=` `number, ``1` `    ``# 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.`

## C#

 `// C# implementation to find``// square root of given number``// upto given precision using``// binary search.``using` `System;``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()``    ``{``        ``// Function calling``        ``Console.WriteLine(squareRoot(50, 3));` `        ``// Function calling``        ``Console.WriteLine(squareRoot(10, 4));``    ``}``}` `// This code is contributed by Sheharaz Sheikh`

## PHP

 ` 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.``?>`

## Javascript

 ``

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)).

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
{"ft_lang_label":"__label__en","ft_lang_prob":0.50032115,"math_prob":0.99086744,"size":8820,"snap":"2021-21-2021-25","text_gpt3_token_len":2480,"char_repetition_ratio":0.18500453,"word_repetition_ratio":0.5118292,"special_character_ratio":0.32358277,"punctuation_ratio":0.13494132,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99966156,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-06-24T16:11:44Z\",\"WARC-Record-ID\":\"<urn:uuid:033fa2dc-6a43-4bfe-ac44-ce97c5c9cabc>\",\"Content-Length\":\"177895\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:3746ddbe-49d4-4657-a9c0-89ce2e5484ee>\",\"WARC-Concurrent-To\":\"<urn:uuid:3dc7e348-38e9-4c18-a31c-68077ec4bb12>\",\"WARC-IP-Address\":\"23.12.144.230\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/find-square-root-number-upto-given-precision-using-binary-search/\",\"WARC-Payload-Digest\":\"sha1:QUEXSF23NZSARAODJYGBTOBBVMQOEAZY\",\"WARC-Block-Digest\":\"sha1:5ZFQ52R6VKUUCURFTGVXUMBZIUCDFOLW\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-25/CC-MAIN-2021-25_segments_1623488556133.92_warc_CC-MAIN-20210624141035-20210624171035-00602.warc.gz\"}"}