Perform divide operation without using '/' operator and give the most efficient solution.
Let us divide x by y
Over the period of time the remainder will grow and when it̢۪s value crosses y we need to add 1 to the quotient because in effect quotient has increased by 1.
Strategy:
Algorithm to divide two numbers using shifting the binary number to the left. Let us divide x by y
int by2(int x): x << 1 // do left shift of x to divide it by 2
divide(x,y):
if(x=0):
return (q,r)=(0,0)
(q,r) = divide (by2(x),y)
q=2*q, r=2*r
if x is odd
r=r+1
if(r>=y)
r=r-y, q=q+1
return (q,r)
by2(x) shift binary x to the left by 1 bit and as a result divides the number
by two. At the same time q and r is multiplied by 2 because we are effectively
dividing x by 2. If x is odd then we need to add 1 to the remainder.Over the period of time the remainder will grow and when it̢۪s value crosses y we need to add 1 to the quotient because in effect quotient has increased by 1.
No comments:
Post a Comment