How to divide big numbers?

Alan picture Alan · Jun 19, 2009 · Viewed 7.4k times · Source

I have a big number (integer, unsigned) stored in 2 variables (as you can see, the high and low part of number):

unsigned long long int high;
unsigned long long int low;

I know how to add or subtract some other that-kind of variable.

But I need to divide that-kind of numbers. How to do it? I know, I can subtract N times, but, maybe, there are more better solutions. ;-)

Language: C

Answer

Erwin Smout picture Erwin Smout · Jun 19, 2009

Yes. It will involve shifts, and I don't recommend doing that in C. This is one of those rare examples where assembler can still prove its value, easily making things run hundreds of times faster (And I don't think I'm exaggerating this.)

I don't claim total correctness, but the following should get you going :

(1) Initialize result to zero.

(2) Shift divisor as many bits as possible to the left, without letting it become greater than the dividend.

(3) Subtract shifted divisor from dividend and add one to result.

(4) Now shift divisor to the right until once again, it is less than the remaining dividend, and for each right-shift, left-shift result by one bit. Go back to (3) unless stopping condition is satisfied. (Stopping condition must be something like "divisor has become zero", but I'm not certain about that.)

It really feels great to get back to some REAL programming problems :-)