Xref: utzoo comp.lang.c:11932 comp.arch:6110 Path: utzoo!utgpu!water!watmath!clyde!att!rutgers!cmcl2!lanl!beta!jlg From: jlg@beta.lanl.gov (Jim Giles) Newsgroups: comp.lang.c,comp.arch Subject: Re: Multiplying two shorts... Message-ID: <21191@beta.lanl.gov> Date: 20 Aug 88 00:18:06 GMT References: <948@srs.UUCP> <8101@alice.UUCP> <864@l.cc.purdue.edu> <1810@vaxb.calgary.UUCP> Organization: Los Alamos National Laboratory Lines: 39 In article <1810@vaxb.calgary.UUCP>, radford@calgary.UUCP (Radford Neal) writes: > int a, b, c, d; > > a = (a*b*c*d) % 10; > > By your logic, the intermediate result (a*b*c*d) should be computed to > 128-bit precision, assuming int's are 32 bits. That's not necessarily true. Your particular example does not require any precision above 32 bits. The exact answer for the given statement is the same as for: int a, b, c, d; a=((a%10)*(b%10)*(c%10)*(d%10))%10 or (with 64-bit intermediates): a=(((a*b)%10) * ((c*d)%10)) %10 Of course, neither of these really works in C because parenthesis don't force execution order. But the compiler is free to do the computation in either way (or any of several other ways). The same is true if some of the multiplies are replaced by adds or subtracts. I tend to agree with those who claim a 'correct' answer is better than a fast answer. The problem is that C doesn't specify what the 'correct' answer is. If C explicitly said that all integer arithmetic should be carried out modulo 2^(wordsize), then (a*b*c*d)%10 should be done the obvious fast way - people who naively assume that the program should give the mathematically 'correct' answer would deserve what they got. On the other hand, if C explicitly said that all integer arithemtic was mathematically exact (as long as the answer didn't overflow), then one of the more careful methods of evaluating the result should be used. This whole problem arises because C (neither K&R nor the ANSI standard) doesn't say how the arithmetic should be done. J. Giles