How do I multiply 2 big integers?
In the previous post I talked about "How do I add 2 big integers?". In the same scenario, consider that now you want to multiply those 2 huge integer numbers... Is the logic the same?
Yes, but the solution is not as simple. Please read the previous post to understand the logic behind the solution, then jump to the code and see my comments bellow.
First, note that we are iterating over both big integer representations as arrays – array1 and array2. On line 22 you can see the product of 2 single-digits items that represent the i-est and j-est digits of both big integers, respectively.
In the previous post I talked about "How do I add 2 big integers?". In the same scenario, consider that now you want to multiply those 2 huge integer numbers... Is the logic the same?
Yes, but the solution is not as simple. Please read the previous post to understand the logic behind the solution, then jump to the code and see my comments bellow.
[Java code snippet] Big integer product |
First, note that we are iterating over both big integer representations as arrays – array1 and array2. On line 22 you can see the product of 2 single-digits items that represent the i-est and j-est digits of both big integers, respectively.
As commented on line 25, if the product has 2 digits, the 2nd one should be stored in the next index. Since the current index is given by i+j, the next one will be i+j+1. To implement this logic, we will iterate over the array representation of this product, called prodAsArray, where k could be 0 or 1 (line 26).
When we are storing each digit on its correct position i+j+k (line 27), we have to add the it to the previous digit that might have been stored in a previous iteration. That's why I used +=. Ops, a sum operation, so the result could also have 2 digits! If it is the case, we have lines 30 to 38 to handle this, following the same logic as described before.