Reputation: 1
I'm doing a bigint project and I am stumped as to why my multiplication operator isn't working properly on a test case.
I'm excluding the .h file because its probably unnecessary.
bigint.cpp:
// Definition of multiplication operator
BigInt BigInt::operator*(BigInt addend2)
{
BigInt product;
short int first, // a block of 1st addend (this object)
second, // a block of 2nd addend (addend2)
result, // a block in their sum
carry = 0; // the carry in adding two blocks
list<short int>::reverse_iterator // to iterate right to left
it1 = myList.rbegin(), // through 1st list, and
it2 = addend2.myList.rbegin(); // through 2nd list
while (it1 != myList.rend() || it2 != addend2.myList.rend())
{
if (it1 != myList.rend())
{
first = *it1;
it1++ ;
}
else
first = 0;
if (it2 != addend2.myList.rend())
{
second = *it2;
it2++ ;
}
else
second = 0;
short int temp = first * second;
result = temp % 1000;
carry = temp / 1000;
product.myList.push_front(result);
}
if (carry > 0)
product.myList.push_front(carry);
return product;
}
Main.cpp (Test case):
int main()
{
char response;
do
{
cout << "\nMultiplication part:" << endl;
cout << "The multiplication of\n\t"
<< number1 << " * " << number2
<< "\nis\n\t" << number1 * number2 << endl;
cout << "\nAdd more integers (Y or N)? ";
cin >> response;
}
When I run the code, the multiplication is wrong.
Below is a sample run: The multiplication of 123 * 423 is -507 which is obviously not correct.
I'm pretty sure I messed up on the definition of the multiplication but can anyone say where I messed up?
Edit: Just letting everyone know, my code does compile, but the product is sometimes wrong. I also change all my short int to long int.
For example:
978 * 878 = 858,684 Which is correct
But when I use bigger numbers then the problem occurs.
Example:
432,454 * 765,534 = 330,722,436 which is not correct. The correct answer is 3.32 * 10^11
Upvotes: 0
Views: 651
Reputation: 42544
Don't use short int
for your intermediate values: 1000 * 1000 will likely overflow a short. Use int
, and ideally somewhere static_assert(1000 * 1000 <= std::numeric_limits<int>::max()), "oops - int is too small!");
.
123 * 423 = 52029. On a two's complement machine with 16 bit shorts, unsigned short(52029) = -13507. -13507 % 1000 = -507. I'm not sure what happened to the carry. though.
Upvotes: 1