I need to do the following arithmetic:
long a,b,c;
long result = a*b/c;
While the result is guaranteed to fit in long
, the multiplication is not, so it can overflow.
I tried to do it step by step (first multiply and then divide) while dealing with the overflow by splitting the intermediate result of a*b
into an int array in size of max 4 ( much like the BigInteger is using its int[] mag
variable).
Here I got stuck with the division. I cannot get my head around the bitwise shifts required to do a precise division. All I need is the quotient (don't need the remainder).
The hypothetical method would be:
public static long divide(int[] dividend, long divisor)
Also, I am not considering using BigInteger
as this part of the code needs to be fast ( I would like to stick to using primitives and primitive arrays).
Any help would be much appreciated!
Edit:
I am not trying to implement the whole BigInteger
myself. What I am trying to do is to solve a specific problem (a*b/c
, where a*b
can overflow) faster than using the generic BigInteger
.
Edit2: It would be ideal if it could be done in a clever way, by not getting overflow at all, some tips surfaced in the comments, but I am still looking for one that is correct.
Update: I tried to port BigInteger code to my specific needs, without object creation, and in the first iteration, I got ~46% improvement in speed comparing to using BigInteger (on my development pc).
Then I tried a bit modified @David Eisenstat solution, which gave me ~56 % (I ran 100_000_000_000 random inputs from Long.MIN_VALUE
to Long.MAX_VALUE
) reduced run times(more than 2x) comparing to BigInteger (that is ~18% compared to my adapted BigInteger algo).
There will be more iterations on optimization and testing, but at this point, I think I must accept this answer as the best.