Multiplying two shorts...

Jim Giles jlg at beta.lanl.gov
Sat Aug 20 10:18:06 AEST 1988


In article <1810 at vaxb.calgary.UUCP>, radford at 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



More information about the Comp.lang.c mailing list