M
MWB
Hi CLC,
Suppose I want to evaluate (x*y)/z where x,y,z are unsigned int's.
In some cases, though (x*y) might overflow the (xy)/z (the actual
product) might be representable as an unsigned int, I was wondering
how to get the correct answer in such a case.
In one specific case the answer is easy to see : x is the only "large"
number among the three- y and z are small.
Then calculate the answer as (x/z)*y + ((x -(x/z)*z)*y)/z
The following program illustrates my point:
#include <stdio.h>
#include <limits.h>
typedef unsigned int uint;
int
main(void)
{
uint x=(UINT_MAX-1)/2,y=4,z=5,w;
w=(x*y)/z;
printf("x=%u y=%u z=%u w=%u\n",x,y,z,w);
w= (x/z)*y + (x - (x/z)*z )*y/z;
printf("x=%u y=%u z=%u w=%u\n",x,y,z,w);
return 0;
}
I was wondering, if the above trick can be extended. Are there some
other ways to deal with such overflows?
TIA,
Suppose I want to evaluate (x*y)/z where x,y,z are unsigned int's.
In some cases, though (x*y) might overflow the (xy)/z (the actual
product) might be representable as an unsigned int, I was wondering
how to get the correct answer in such a case.
In one specific case the answer is easy to see : x is the only "large"
number among the three- y and z are small.
Then calculate the answer as (x/z)*y + ((x -(x/z)*z)*y)/z
The following program illustrates my point:
#include <stdio.h>
#include <limits.h>
typedef unsigned int uint;
int
main(void)
{
uint x=(UINT_MAX-1)/2,y=4,z=5,w;
w=(x*y)/z;
printf("x=%u y=%u z=%u w=%u\n",x,y,z,w);
w= (x/z)*y + (x - (x/z)*z )*y/z;
printf("x=%u y=%u z=%u w=%u\n",x,y,z,w);
return 0;
}
I was wondering, if the above trick can be extended. Are there some
other ways to deal with such overflows?
TIA,