xref: /dragonfly/contrib/gmp/mpz/mod.c (revision e5a92d33)
1 /* mpz_mod -- The mathematical mod function.
2 
3 Copyright 1991, 1993, 1994, 1995, 1996, 2001, 2002, 2005 Free Software
4 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 divisor_size = divisor->_mp_size;
28   mpz_t temp_divisor;		/* N.B.: lives until function returns! */
29   TMP_DECL;
30 
31   TMP_MARK;
32 
33   /* We need the original value of the divisor after the remainder has been
34      preliminary calculated.  We have to copy it to temporary space if it's
35      the same variable as REM.  */
36   if (rem == divisor)
37     {
38       MPZ_TMP_INIT (temp_divisor, ABS (divisor_size));
39       mpz_set (temp_divisor, divisor);
40       divisor = temp_divisor;
41     }
42 
43   mpz_tdiv_r (rem, dividend, divisor);
44 
45   if (rem->_mp_size != 0)
46     {
47       if (dividend->_mp_size < 0)
48 	{
49 	  if (divisor->_mp_size < 0)
50 	    mpz_sub (rem, rem, divisor);
51 	  else
52 	    mpz_add (rem, rem, divisor);
53 	}
54     }
55 
56   TMP_FREE;
57 }
58