1 /*
2     Copyright (C) 2020 Daniel Schultz
3 
4     This file is part of FLINT.
5 
6     FLINT is free software: you can redistribute it and/or modify it under
7     the terms of the GNU Lesser General Public License (LGPL) as published
8     by the Free Software Foundation; either version 2.1 of the License, or
9     (at your option) any later version.  See <https://www.gnu.org/licenses/>.
10 */
11 
12 #include <gmp.h>
13 #include "flint.h"
14 #include "ulong_extras.h"
15 #include "fmpz.h"
16 
fmpz_cdiv_r_2exp(fmpz_t f,const fmpz_t g,ulong exp)17 void fmpz_cdiv_r_2exp(fmpz_t f, const fmpz_t g, ulong exp)
18 {
19     fmpz d = *g;
20 
21     if (!COEFF_IS_MPZ(d))  /* g is small */
22     {
23         if (d <= 0)
24         {
25             d = -d;
26             fmpz_neg_ui(f, exp < (FLINT_BITS - 2) ? d & ((WORD(1) << exp) - 1) : d);
27         }
28         else
29         {
30             if (exp <= FLINT_BITS - 2)
31             {
32                 fmpz_neg_ui(f, (-d) & ((WORD(1) << exp) - 1));
33             }
34             else
35             {
36                 __mpz_struct * mpz_ptr = _fmpz_promote(f);
37 
38                 flint_mpz_set_ui(mpz_ptr, 1);
39                 mpz_mul_2exp(mpz_ptr, mpz_ptr, exp);
40                 flint_mpz_sub_ui(mpz_ptr, mpz_ptr, d);
41                 mpz_neg(mpz_ptr, mpz_ptr);
42             }
43         }
44     }
45     else  /*g is large */
46     {
47         __mpz_struct * mpz_ptr = _fmpz_promote(f);  /* g is already large */
48         mpz_cdiv_r_2exp(mpz_ptr, COEFF_TO_PTR(d), exp);
49         _fmpz_demote_val(f);  /* division may make value small */
50     }
51 }
52 
53