I’m searching for an algorithm to solve differences of the type ab-cd, where a, b, c, and d are integers at the edge of the type capacity, i.e. ab overflows or loses digits depending on the actual representation on the machine. I cannot use arbitrary precision math; one of the platforms will be a SQL database.
I consider something like decomposing the product into (a’+a”)b-(c’+c”)d and then somehow iterate the way down. But probably there is a much more efficient method or at least a clever idea how to do the decomposition. Unfortunately in most cases a,b; c,d; a,c; b,d are coprime, so reduction at least is not simple.
Any ideas?
The standard way I know of to address this type of issues is to do what humans do with numbers beyond one digit, which is the limit of our natural counting with fingers. We
carrynumbers forward.For example, let’s say the limit of numbers in your numeric calculator is 256 (2^8). To get the difference of (243*244)-(242*245), we would need to decompose the numbers into
You’d need an array to store the individual digits of the result, or a string. I think an array is faster, but a string more convenient and visible (for debugging).
A naive implementation would work through each step independently, pushing each digit into place and carrying it forward where necessary. There are probably tomes of literature about optimizing these algorithms, such as breaking this into array slots of 2 digits each (since your register of number-limit 256 can handle the addition of 2 2-digit numbers easily).