jeudi 27 mai 2010

Implement division without using * / %

I'll start by implementing multiplication to warm up

The first function relies on binary operation (shr and shl). It is way too complex but it is the first one I came up with. It looks ok but I haven't checked it. The second one is what I should have come up with at first.


def multiply (n,p)
r = 0
while p
p2 = shr (p)
if (p == 2*p + 1)
r += n
n = shl(n)
p = p2
return r

def multiply2 (n,p)
r = 0
for k = 0 ; k < p k++
r += n
return r



Now for division, we understand that it will be almost as easy as multiply2.
General idea: we need to find q so that n = pq+r with r < p

Aucun commentaire:

Enregistrer un commentaire