Search code examples
java

How to write own multiplication of big numbers?


For my homework, I have to deal with multiplication of big numbers ( greater then java.long ) stared in my own BigNumber class as int[]. Basically I need to implement something like this :

    157 x
    121 y
   ----
    157 result1
   314  + result2
  157   + result3
 ------
 18997  finalResult

But how do I implement it?

I thought about expanding result2,3 with zeros (3140, 15700) and adding them. But first I somehow need to navigate between each digit of y and multiply it by each digit of x.


Solution

  • Use the diagonal approach. Make an array, and multiply each digit by each other digit and fill in the numbers in each cell.

    36 x 92
    
           3     6
        +-----+-----+
        | 2 / | 5 / |
    9   |  /  |  /  |
        | / 7 | / 4 |
        +-----+-----+
        | 0 / | 1 / |
    2   |  /  |  /  |
        | / 6 | / 2 |
        +-----+-----+
    

    Add the numbers on each diagonal. Move from the least-significant digit (at the lower right) to the most (upper left).

    2                                                                    2 (least-significant)
    (6 + 1 + 4) = 11 (make this 1, and carry the 1 to the next digit)    1
    (5 + 7 + 0 + 1(carried)) = 13 (make this 3, and carry the 1)         3
    2 + 1(carried) = 3                                                   3 (most-significant)
    

    The answer's 3312.

    Make a two-dimensional array of your digits. Fill the array with the multiplications of the single digits together.

    Write some logic to scrape the diagonals as I did above.

    This should work for arbitrarily large numbers (as long as you still have memory left).