An interview question.
How to implement division by addition? suppose they are all int.
My idea
quotient * divisor + reminder == dividend
. It is O(e^n)
, any better ideas? bit operation?
dividing m
by n
:
int r = m;
int q = 0;
while( r >= n )
{
int k = 1;
int x = n;
int t;
while( ( t = x+x ) < r )
{
x = t;
k += k;
}
q += k;
r -= x;
}
The result is q
- quotient, r
- remainder.
The idea is that x+x
is the same as x*2
.
UPD:
Some may complain that r -= x
is not addition.
Well we may update the algorithm to not use subtraction:
int p = 0;
int q = 0;
while( p+n <= m )
{
int k = 1;
int x = n;
int t;
while( p + ( t = x+x ) < m )
{
x = t;
k += k;
}
q += k;
p += x;
}
The result is q
- quotient.
If we need the remainder then we proceed as follows (p
- output from the above):
int r = 0;
while( p < m )
{
int x = 1;
int t;
while( p + ( t = x+x ) < m )
{
x = t;
}
r += x;
p += x;
}
The result is r
- remainder.
The algorithm has obviously polynomial (not exponential) running-time.
In digital arithmetic we can name restoring and non-restoring methods as simple division algorithms which are based on addition/subtraction. Number of iterations in these methods are of O(n)
(where n
is the number of bits). There are methods like Newton-Raphson or reciprocal calculation which are based on multiplication and number of iterations in them are of O(log n)
. Take a look at http://en.wikipedia.org/wiki/Division_%28digital%29
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With