r6831@lvps87-230-33-50: verhaegs | 2008-02-03 14:08:57 +0100
[tangerine.git] / compiler / clib / div.c
blobbc5a17ba386b81c8b83e015142c22e66d3013d89
1 /*
2 Copyright © 1995-2002, The AROS Development Team. All rights reserved.
3 $Id$
5 ISO C function div().
6 */
8 /*****************************************************************************
10 NAME */
11 #include <stdlib.h>
13 div_t div (
15 /* SYNOPSIS */
16 int numer,
17 int denom)
19 /* FUNCTION
20 Compute quotient en remainder of two int variables
22 INPUTS
23 numer = the numerator
24 denom = the denominator
26 RESULT
27 a struct with two ints quot and rem with
28 quot = numer / denom and rem = numer % denom.
30 typedef struct div_t {
31 int quot;
32 int rem;
33 } div_t;
35 NOTES
37 EXAMPLE
39 BUGS
41 SEE ALSO
42 ldiv()
44 INTERNALS
46 ******************************************************************************/
48 div_t ret;
50 ret.quot = numer / denom;
51 ret.rem = numer % denom;
54 This comment is from FreeBSD's src/lib/libc/stdlib/div.c, but
55 the code was written before the comment was added (see CVS log).
57 Thus the code isn't really under the BSD license. The comment is...
61 * The ANSI standard says that |r.quot| <= |n/d|, where
62 * n/d is to be computed in infinite precision. In other
63 * words, we should always truncate the quotient towards
64 * 0, never -infinity.
66 * Machine division and remainer may work either way when
67 * one or both of n or d is negative. If only one is
68 * negative and r.quot has been truncated towards -inf,
69 * r.rem will have the same sign as denom and the opposite
70 * sign of num; if both are negative and r.quot has been
71 * truncated towards -inf, r.rem will be positive (will
72 * have the opposite sign of num). These are considered
73 * `wrong'.
75 * If both are num and denom are positive, r will always
76 * be positive.
78 * This all boils down to:
79 * if num >= 0, but r.rem < 0, we got the wrong answer.
80 * In that case, to get the right answer, add 1 to r.quot and
81 * subtract denom from r.rem.
83 if (numer >= 0 && ret.rem < 0)
85 ret.quot++;
86 ret.rem -= denom;
88 return ret;