Expand|Select|Wrap|Line Numbers
- public void multiply (VeryLongInt otherVeryLong)
- {
- final int BASE = 10;
- int largerSize, partialProduct, carry = 0;
- int i = 0, j = 0; // i is the bottom factor LSD, j the upper factor LSD
- largerSize = (digits.size() + otherVeryLong.digits.size()) - 1; // 5 digit quantity * another 5 digit quantity = 9 digit quantity
- ArrayList<Integer> productDigits = new ArrayList<Integer>(largerSize);
- for (otherVeryLong.least(i); i < otherVeryLong.digits.size(); i++)
- {
- for (least(j); j < digits.size(); j++)
- {
- partialProduct = (least(j) * otherVeryLong.least(i)) + carry;
- carry = partialProduct / BASE;
- productDigits.add (partialProduct % BASE);
- }
- }
- Collections.reverse (productDigits);
- digits = productDigits;
- }
The two numbers I'm trying to multiply are 12,345 and 51,612. I'll try to explain the situation clearly.
I've used two for loops, one nested in the other, to take each digit from the bottom multiplicand (starting from the one's place) and multiply it by each digit in the upper multiplicand. It should then move on to the tens place in the bottom multiplicand and multiply that by all the digits in the upper multiplicand, and so on.
Curiously, after execution, my productDigits ArrayList only seems to hold the product of the one's place number in the bottom multiplicand times the upper multiplicand (12,345 x 2 = .24,960). I would have thought that it would hold 12,345 x 5, which should be the latest value.
Anyway, in addition to that, I'm not sure how add together all of the products to get the final result. I know that I will have to shift the places over somehow, but I don't know what approach to take. Do I need to make more ArrayLists to hold each product, then sum them together afterwards?
I've been working on this for a while and am starting to get frustrated. Can anyone give me some general tips to point me in the right direction? Of course, if that's against the rules (as this is part of a homework assignment), then no problem.