Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quotient and remainder for division a product of big integers by a big integer

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?

like image 258
Loom Avatar asked Dec 05 '25 10:12

Loom


1 Answers

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?

like image 161
freakish Avatar answered Dec 07 '25 23:12

freakish