Reputation: 81
Hello All I have been working on a big integer class and I have finished addition and subtraction and I now am currently trying to write a working Multiplication function but if I am multiplying a really big number after the first 3 digits it looses precision and the answer is wrong. Could anyone help me with what I am doing wrong here I can't think of anything?
BigInt operator*(const BigInt& left, const BigInt& right)
{
BigInt temp1 = left;
BigInt temp2 = right;
temp1.sign = 1;
temp2.sign = 1;
BigInt Max = MAX(temp1, temp2), Min = MIN(temp1, temp2);
ArrayList<char> temp_container = ArrayList<char>();
ArrayList<BigInt> nums = ArrayList<BigInt>();
int carry = 0;
int zero_count = 0;
for (int i = Min.Digits.size() - 1; i > -1; i--)
{
for (int j = Max.Digits.size() - 1; j > -1; j--)
{
int temp = (Max.Digits.get(j) * Min.Digits.get(i)) + carry;//Multiply Digits
if (temp < 10)//if it is a digit
{
temp_container.add_to_front(temp + '0');
carry = 0;
}
//else if it isnt a digit
else if (temp >= 10 && j > 0)
{
temp_container.add_to_front((temp / 10) + '0');
carry = temp % 10;
}
else if (temp >= 10 && j < 0)
{
temp_container.add_to_front((temp / 10) + '0');
temp_container.add_to_front((temp % 10) + '0');
}
}
for (int j = 0; j < zero_count; j++)
{
temp_container.add('0');
}
nums.add(BigInt(temp_container));
temp_container.removeAll();
zero_count++;//increase the amount of zeros to add to the next number
}
BigInt result = BigInt("0");
for (int i = 0; i < nums.size(); i++)
{
result += nums.get(i);//add all of the number up
}
//determine if positive or negative
if (left.sign == right.sign)
{
result.sign = 1;
}
else
{
result.sign = -1;
}
return result;
}
Upvotes: 1
Views: 2033
Reputation: 49803
You have your carry and your digit reversed (when there is a carry).
Upvotes: 2