Upload Tizen:Base source
[external/gmp.git] / mpbsd / sdiv.c
1 /* sdiv -- Divide a MINT by a short integer.  Produce a MINT quotient
2    and a short remainder.
3
4 Copyright 1991, 1994, 1995, 2000, 2001 Free Software Foundation, Inc.
5
6 This file is part of the GNU MP Library.
7
8 The GNU MP Library is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or (at your
11 option) any later version.
12
13 The GNU MP Library is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
16 License for more details.
17
18 You should have received a copy of the GNU Lesser General Public License
19 along with the GNU MP Library.  If not, see http://www.gnu.org/licenses/.  */
20
21 #include "mp.h"
22 #include "gmp.h"
23 #include "gmp-impl.h"
24 #include "longlong.h"
25
26 void
27 sdiv (const MINT *dividend, signed short int divisor_short, MINT *quot, short *rem_ptr)
28 {
29   mp_size_t sign_dividend;
30   signed long int sign_divisor;
31   mp_size_t dividend_size, quot_size;
32   mp_ptr dividend_ptr, quot_ptr;
33   mp_limb_t divisor_limb;
34   mp_limb_t remainder_limb;
35
36   sign_dividend = dividend->_mp_size;
37   dividend_size = ABS (dividend->_mp_size);
38
39   if (dividend_size == 0)
40     {
41       quot->_mp_size = 0;
42       *rem_ptr = 0;
43       return;
44     }
45
46   sign_divisor = divisor_short;
47   divisor_limb = (unsigned short) ABS (divisor_short);
48
49   /* No need for temporary allocation and copying even if QUOT == DIVIDEND
50      as the divisor is just one limb, and thus no intermediate remainders
51      need to be stored.  */
52
53   if (quot->_mp_alloc < dividend_size)
54     _mp_realloc (quot, dividend_size);
55
56   quot_ptr = quot->_mp_d;
57   dividend_ptr = dividend->_mp_d;
58
59   remainder_limb = mpn_divmod_1 (quot_ptr,
60                                  dividend_ptr, dividend_size, divisor_limb);
61
62   *rem_ptr = sign_dividend >= 0 ? remainder_limb : -remainder_limb;
63   /* The quotient is DIVIDEND_SIZE limbs, but the most significant
64      might be zero.  Set QUOT_SIZE properly. */
65   quot_size = dividend_size - (quot_ptr[dividend_size - 1] == 0);
66   quot->_mp_size = (sign_divisor ^ sign_dividend) >= 0 ? quot_size : -quot_size;
67 }