-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDivisionUsingBinarySearch.cpp
More file actions
59 lines (48 loc) · 922 Bytes
/
DivisionUsingBinarySearch.cpp
File metadata and controls
59 lines (48 loc) · 922 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <vector>
// QUESTION: https://www.techiedelight.com/division-two-numbers-using-binary-search-algorithm/
class Divide
{
private:
int num;
int den;
public:
Divide(int a, int b)
: num(a), den(b)
{
}
double compute()
{
// we want to compute result = x/y
// or x = result*y
if (den == 0)
return std::numeric_limits<double>::infinity();
int sign = 1;
if ((num ^ den) < 0)
sign = -1;
double precision = 0.001;
double low = 0;
double high = std::numeric_limits<double>::max();
double result = 0;
while (1)
{
result = low + (high - low) / 2;
double temp = result*den;
if (std::abs(temp - num) <= precision)
return result*sign;
if (temp > num)
{
high = result;
} else {
low = result;
}
}
}
};
int main()
{
Divide obj(22, 7);
double result = obj.compute();
std::cout << "22/7 is " << result << std::endl;
return 0;
}