3 <<lldiv>>---divide two long long integers
10 lldiv_t lldiv(long long <[n]>, long long <[d]>);
20 returning quotient and remainder as two long long integers in a structure
24 The result is represented with the structure
32 where the <<quot>> field represents the quotient, and <<rem>> the
33 remainder. For nonzero <[d]>, if `<<<[r]> = ldiv(<[n]>,<[d]>);>>' then
34 <[n]> equals `<<<[r]>.rem + <[d]>*<[r]>.quot>>'.
36 To divide <<long>> rather than <<long long>> values, use the similar
40 <<lldiv>> is ISO 9899 (C99) compatable.
42 No supporting OS subroutines are required.
46 * Copyright (c) 2001 Mike Barcroft <mike@FreeBSD.org>
47 * All rights reserved.
49 * Redistribution and use in source and binary forms, with or without
50 * modification, are permitted provided that the following conditions
52 * 1. Redistributions of source code must retain the above copyright
53 * notice, this list of conditions and the following disclaimer.
54 * 2. Redistributions in binary form must reproduce the above copyright
55 * notice, this list of conditions and the following disclaimer in the
56 * documentation and/or other materials provided with the distribution.
58 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
74 * The ANSI standard says that |r.quot| <= |n/d|, where
75 * n/d is to be computed in infinite precision. In other
76 * words, we should always truncate the quotient towards
79 * Machine division and remainer may work either way when
80 * one or both of n or d is negative. If only one is
81 * negative and r.quot has been truncated towards -inf,
82 * r.rem will have the same sign as denom and the opposite
83 * sign of num; if both are negative and r.quot has been
84 * truncated towards -inf, r.rem will be positive (will
85 * have the opposite sign of num). These are considered
88 * If both are num and denom are positive, r will always
91 * This all boils down to:
92 * if num >= 0, but r.rem < 0, we got the wrong answer.
93 * In that case, to get the right answer, add 1 to r.quot and
94 * subtract denom from r.rem.
97 lldiv (long long numer
, long long denom
)
101 retval
.quot
= numer
/ denom
;
102 retval
.rem
= numer
% denom
;
103 if (numer
>= 0 && retval
.rem
< 0) {