I have the following code
int i, a, z;
i = 2343243443;
a = 5464354324324324;
z = i * a;
cout << z << endl;
When these are multiplied it gives me -1431223188 which is not the answer. How can I make it give me the correct answer?
How Does it Work? Multiplying large numbers together is performed by multiplying the ones digit of the bottom number to the entire top number. After the ones place value has finished multiplying, move to the tens place value in the bottom number and multiply that digit by the top number.
Usually, you would choose a base that is half the largest representable type so that there are no overflows. For instance, in modern C, you would choose uint32_t and do all the digit arithmetic in uint64_t . And don't forget: make the digit type unsigned so that there are no surprises.
Program to Multiply Two Numbersprintf("Enter two numbers: "); scanf("%lf %lf", &a, &b); Then, the product of a and b is evaluated and the result is stored in product . product = a * b; Finally, product is displayed on the screen using printf() .
The result overflows the int (and also std::uint64_t
)
You have to use some BigInt library.
As Jarod42 suggested is perfectly okay, but i am not sure whether overflow will take place or not ?
Try to store each and every digit of number in an array and after that multiply. You will definitely get the correct answer.
For more detail how to multiply using array follow this post http://discuss.codechef.com/questions/7349/computing-factorials-of-a-huge-number-in-cc-a-tutorial
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With