xref: /netbsd-src/external/lgpl3/gmp/dist/mpz/mod.c (revision 80d9064ac03cbb6a4174695f0d5b237c8766d3d0)
1 /* mpz_mod -- The mathematical mod function.
2 
3 Copyright 1991, 1993, 1994, 1995, 1996, 2001, 2002, 2005, 2010, 2012
4 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 "gmp.h"
22 #include "gmp-impl.h"
23 
24 void
25 mpz_mod (mpz_ptr rem, mpz_srcptr dividend, mpz_srcptr divisor)
26 {
27   mp_size_t rn, bn;
28   mpz_t temp_divisor;
29   TMP_DECL;
30 
31   TMP_MARK;
32 
33   bn = ABSIZ(divisor);
34 
35   /* We need the original value of the divisor after the remainder has been
36      preliminary calculated.  We have to copy it to temporary space if it's
37      the same variable as REM.  */
38   if (rem == divisor)
39     {
40       PTR(temp_divisor) = TMP_ALLOC_LIMBS (bn);
41       MPN_COPY (PTR(temp_divisor), PTR(divisor), bn);
42     }
43   else
44     {
45       PTR(temp_divisor) = PTR(divisor);
46     }
47   SIZ(temp_divisor) = bn;
48   divisor = temp_divisor;
49 
50   mpz_tdiv_r (rem, dividend, divisor);
51 
52   rn = SIZ (rem);
53   if (rn < 0)
54     mpz_add (rem, rem, divisor);
55 
56   TMP_FREE;
57 }
58