This post will discuss the division of two numbers (integer or decimal) using the binary search algorithm.

We can easily modify the binary search algorithm to perform the division of two decimal numbers. We start by defining the range for our result as [0, INFINITY], which is the initial low and high for the binary search algorithm. Now we need to find a mid that satisfies x / y = mid or x = y × mid for given two numbers, x and y, which will be our result.

Based on a comparison result between x and y × mid, either update low or high, or return mid if:

  • y × mid is almost equal to x, return mid.
  • y × mid is less than x, update low to mid.
  • y × mid is more than x, update high to mid.

We also need to take care of a few conditions like divisibility by 0, the result’s sign, etc., as demonstrated in below in C, Java, and Python:

C


Download  Run Code

Output:

3.142822

Java


Download  Run Code

Output:

3.1428222656249996

Python


Download  Run Code

Output:

3.1428222656249996

The time complexity of the above solution is O(log(n)), where n is equal to MAX_VAL.