xref: /dragonfly/contrib/gmp/mpn/generic/redc_n.c (revision e0b1d537)
1 /* mpn_redc_n.  Set cp[] <- up[]/R^n mod mp[].  Clobber up[].
2    mp[] is n limbs; up[] is 2n limbs, the inverse ip[] is n limbs.
3 
4    THIS IS AN INTERNAL FUNCTION WITH A MUTABLE INTERFACE.  IT IS ONLY
5    SAFE TO REACH THIS FUNCTION THROUGH DOCUMENTED INTERFACES.
6 
7 Copyright (C) 2009 Free Software Foundation, Inc.
8 
9 This file is part of the GNU MP Library.
10 
11 The GNU MP Library is free software; you can redistribute it and/or modify
12 it under the terms of the GNU Lesser General Public License as published by
13 the Free Software Foundation; either version 3 of the License, or (at your
14 option) any later version.
15 
16 The GNU MP Library is distributed in the hope that it will be useful, but
17 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
18 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
19 License for more details.
20 
21 You should have received a copy of the GNU Lesser General Public License
22 along with the GNU MP Library.  If not, see http://www.gnu.org/licenses/.  */
23 
24 #include "gmp.h"
25 #include "gmp-impl.h"
26 
27 /*
28   TODO
29 
30   * We assume mpn_mulmod_bnm1 is always faster than plain mpn_mul_n (or a
31     future mpn_mulhi) for the range we will be called.  Follow up that
32     assumption.
33 
34   * Decrease scratch usage.
35 */
36 
37 void
38 mpn_redc_n (mp_ptr rp, mp_ptr up, mp_srcptr mp, mp_size_t n, mp_srcptr ip)
39 {
40   mp_ptr xp, yp, scratch;
41   mp_limb_t cy;
42   mp_size_t rn;
43   TMP_DECL;
44   TMP_MARK;
45 
46   rn = mpn_mulmod_bnm1_next_size (n);
47 
48   scratch = TMP_ALLOC_LIMBS (n + rn + mpn_mulmod_bnm1_itch (rn, n, n));
49 
50   xp = scratch;
51   mpn_mullo_n (xp, up, ip, n);
52 
53   yp = scratch + n;
54   mpn_mulmod_bnm1 (yp, rn, xp, n, mp, n, scratch + n + rn);
55 
56   ASSERT_ALWAYS (2 * n > rn);				/* could handle this */
57 
58   cy = mpn_sub_n (yp + rn, yp, up, 2*n - rn);		/* undo wrap around */
59   MPN_DECR_U (yp + 2*n - rn, rn, cy);
60 
61   cy = mpn_sub_n (rp, up + n, yp + n, n);
62   if (cy != 0)
63     mpn_add_n (rp, rp, mp, n);
64 
65   TMP_FREE;
66 }
67