Commit | Line | Data |
---|---|---|
b374846a | 1 | /* |
7860c229 KB |
2 | * Copyright (c) 1990, 1993 |
3 | * The Regents of the University of California. All rights reserved. | |
b374846a KB |
4 | * |
5 | * This code is derived from software contributed to Berkeley by | |
6 | * Chris Torek. | |
7 | * | |
8 | * %sccs.include.redist.c% | |
9 | */ | |
10 | ||
11 | #if defined(LIBC_SCCS) && !defined(lint) | |
7860c229 | 12 | static char sccsid[] = "@(#)div.c 8.1 (Berkeley) %G%"; |
b374846a KB |
13 | #endif /* LIBC_SCCS and not lint */ |
14 | ||
15 | #include <stdlib.h> /* div_t */ | |
16 | ||
b374846a KB |
17 | div_t |
18 | div(num, denom) | |
19 | int num, denom; | |
20 | { | |
21 | div_t r; | |
22 | ||
b374846a KB |
23 | r.quot = num / denom; |
24 | r.rem = num % denom; | |
ad12d145 CT |
25 | /* |
26 | * The ANSI standard says that |r.quot| <= |n/d|, where | |
27 | * n/d is to be computed in infinite precision. In other | |
28 | * words, we should always truncate the quotient towards | |
29 | * 0, never -infinity. | |
30 | * | |
31 | * Machine division and remainer may work either way when | |
32 | * one or both of n or d is negative. If only one is | |
33 | * negative and r.quot has been truncated towards -inf, | |
34 | * r.rem will have the same sign as denom and the opposite | |
35 | * sign of num; if both are negative and r.quot has been | |
36 | * truncated towards -inf, r.rem will be positive (will | |
37 | * have the opposite sign of num). These are considered | |
38 | * `wrong'. | |
39 | * | |
40 | * If both are num and denom are positive, r will always | |
41 | * be positive. | |
42 | * | |
43 | * This all boils down to: | |
44 | * if num >= 0, but r.rem < 0, we got the wrong answer. | |
45 | * In that case, to get the right answer, add 1 to r.quot and | |
46 | * subtract denom from r.rem. | |
47 | */ | |
48 | if (num >= 0 && r.rem < 0) { | |
49 | r.quot++; | |
50 | r.rem -= denom; | |
b374846a KB |
51 | } |
52 | return (r); | |
53 | } |