Modulo arithmetic (was: perpetual calendar (also day of week))
Robert_A_Freed at cup.portal.com
Robert_A_Freed at cup.portal.com
Fri Feb 12 12:28:44 AEST 1988
In article <8802101657.AA08427 at decwrl.dec.com> fulton at navion.dec.com
writes about a formula, for calculating the day of the week for a given
date, which was recently posted in sci.math.
> Then you have -1 MOD 7 => -1, which does not equate to any of
> the numbers assigned to Sunday thru Saturday, namely 0 thru 6.
This depends upon how one defines the MOD (modulo) operation.
Mathematicians usually consider only final results which are positive.
I.e. in your example, -1 MOD 7 => 6. Computer languages and/or library
functions usually generate the signed division remainder as you've
shown, e.g. Fortran's MOD function.
(I was going to cite the C `%' operator, but I just consulted Harbison
and Steele and found the following of interest: "When both operands
are positive, the remainder operation will always be equivalent to the
mathematical ``mod'' operation. Note that this completely specifies
the behavior of the remainder operation for unsigned operands. If
either operand is negative, the behavior will be machine dependent in a
manner corresponding to the machine dependence of integer division.
For maximum portability, programs should therefore avoid depending on
the behavior of the remainder operator when applied to negative
integral operands.")
> perhaps the
> original formula could be changed so that the result doesn't
> require "fixing" if it comes out negative.
>
> - Cathy Fulton
>
> uucp: ...decwrl!comet.dec.com!fulton
> ARPA: fulton at comet.dec.com
Easy: Change the -2C term to +5C. Same result modulo 7.
Bob Freed Internet: Robert_A_Freed at cup.portal.com
Newton Centre, MA UUCP: ...!sun!portal!cup.portal.com!Robert_A_Freed
More information about the Comp.lang.c
mailing list