Suppose we have a positive number n, and precision p. We have to find square root of the number n up to p decimal places using binary search technique. So if the number is n = 50, and p = 3, then output is 7.071.
So solve this, we have to follow some steps −
- Initialize start := 0 and end := n
- Compare the square of mid integer, if this is equal to the number then integral part has found out, otherwise look for left or right as required.
- Once we have completed the task for integral part, then do for the fractional part.
- Initialize increment variable as 0.1, then compute fractional part up to p places. For each iteration increment changes to 1/10 th of its previous value.
- Finally return the answer.
Example
#include<iostream>
using namespace std;
float sqrtBinarySearch(int num, int p) {
int left = 0, right = num;
int mid;
float res;
while (left <= right) {
mid = (left + right) / 2;
if (mid * mid == num) {
res = mid;
break;
}
if (mid * mid < num) {
left = mid + 1;
res = mid;
} else {
right = mid - 1;
}
}
float incr = 0.1;
for (int i = 0; i < p; i++) {
while (res * res <= num) {
res += incr;
}
res -= incr;
incr /= 10;
}
return res;
}
int main() {
int n = 50, p = 3;
cout << "Square root of " << n << " up to precision " << p << " is: " << sqrtBinarySearch(50, 3) << endl;
}Output
Square root of 50 up to precision 3 is: 7.071