440,666 Members | 1,909 Online Need help? Post your question and get tips & solutions from a community of 440,666 IT Pros & Developers. It's quick & easy.

# Dealing with possible overflows

 P: n/a 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 #include 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, Nov 14 '05 #1 