Find square root of number upto given precision using binary search
Last Updated :
14 Sep, 2024
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 <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;
}
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
JavaScript
<script>
// JavaScript program 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)
{
let start = 0, end = number;
let mid;
// variable to store the answer
let 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
let increment = 0.1;
for (let 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
document.write(squareRoot(50, 3) + "<br/>");
// Function calling
document.write(squareRoot(10, 4) + "<br/>");
</script>
PHP
<?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.
?>
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)).
Auxiliary Space: O(1) since it is using constant space for variables
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read