Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.1 6/24/83 (MC840302); site mcvax.UUCP Path: utzoo!watmath!clyde!burl!ulysses!mhuxl!houxm!vax135!cornell!uw-beaver!tektronix!hplabs!hao!seismo!mcvax!guido From: guido@mcvax.UUCP (Guido van Rossum) Newsgroups: net.lang.c Subject: Re: modulus fn with negatives Message-ID: <5972@mcvax.UUCP> Date: Mon, 10-Sep-84 17:25:56 EDT Article-I.D.: mcvax.5972 Posted: Mon Sep 10 17:25:56 1984 Date-Received: Fri, 14-Sep-84 07:27:55 EDT References: <13079@sri-arpa.UUCP> <8213@umcp-cs.UUCP> Reply-To: guido@mcvax.UUCP (Guido van Rossum) Organization: "Stamp Out BASIC" Committee, CWI, Amsterdam Lines: 22 How about this modulus function: mod(a, b) { int m = a % b; if ((m < 0) != (b < 0)) m += b; return m; } This one even works for negative b. You can also do the following: #define mod(a, b) (a%b + b) % b which should, of course, be written as #define mod(a, b) (((a)%(b) + (b)) % (b)) and this also works for negative b (but watch side effects!). -- Guido van Rossum, "Stamp Out BASIC" Committee, CWI, Amsterdam guido @ mcvax