Search code examples
matharraylistcustom-data-type

How do you multiply large numbers of unknown length


I have two numbers I need multiplied together. Problem is that they're too big to fit in any basic data types, so I can't just use an intor long. I have an array list of integers, each representing 6 digits of the overall number.

example: (using letters instead of numbers) abc,def,ghi,jkl,mno,pqr -> [mnopqr, ghijkl, abcdef] (I hope that makes sense)

I can go over the 6 digit limit for each integer then use a function I have to "standardize" it to the right format. (as long as it doesn't go over Integer.MAX) Though I could probably switch them for longs instead.

The question is, how to multiply extremely large numbers of unknown length that is split into segments of 6 digits?

My best guess would be to multiply each segment by each segment: [0]x[0], [0]x[1], [0]x[2]... [1]x[0], [1]x[1], [1]x[2]...

Then add the results to an output number, adding into the segment number either N+N or NxN. But I don't know how the math checks out on that.


Solution

  • You are effectively asking how to implement "BigInt" (or arbitrary precision arithmetic).

    I don't understand the extra commans in abc,def,ghi,jkl,mno,pqr, since you seem to describe it as abcdef,ghijkl,mnopqr, but regardless, the math works out as:

    a = sum_i a_i*10^(3*i)
    b = sum_j b_j*10^(3*j)
    
    c = a*b = ( sum_i a_i*10^(3*i) ) * ( sum_j b_j*10^(3*j) )
            = sum_i sum_j a_i*b_j*10^(3*(i+j))
    

    You'd have to compute into which 10^x offset each segment each contribution went in to, then handle overflow. This seems quite painful and error prone to me.

    Most languages will have some framework for this thing in place already, Java has BigInteger built in, C has GMP.

    If the 6-digit segments is a required format, then I would still just suggest converting that to a String, construct a BigInteger, and splitting that string up again afterwards rather than reinventing the math.