long long signed A, B, C;
or
long long unsigned A, B, C;
I need to calculate quotient and remainder for expression A * B / C, where A,B,C are big integers, so that product A * B causes an overflow and A < C and B < C. Prohibited the use of floating point numbers and the use of third-party libraries. How it can be done?
Remainder of A*B/C is equal to the product of remainders A/C and B/C modulo C again.
//EDIT: Ups, didn't see the conditions A<C, B<C. In that case try something like this:
tmp = A;
for (var i = 1; i<=B; i++)
{
if (tmp + A == overflow || tmp + A >= C)
tmp -= C;
tmp += A;
}
The resulting tmp should be the remainder you seek. This will work as long as all of the inputs are positive and we are doing this in signed situation. Perhaps it will work for unsigned as well, didn't check it though.
Of course you need some fancy function to check the oveflow condition.
As for the quotient you can just evaluate A/C and then multiply it by B, can't you?
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