1 /*
2     Copyright (C) 2009 William Hart
3     Copyright (C) 2011 Sebastian Pancratz
4 
5     This file is part of FLINT.
6 
7     FLINT is free software: you can redistribute it and/or modify it under
8     the terms of the GNU Lesser General Public License (LGPL) as published
9     by the Free Software Foundation; either version 2.1 of the License, or
10     (at your option) any later version.  See <http://www.gnu.org/licenses/>.
11 */
12 
13 #include <gmp.h>
14 #include "flint.h"
15 #include "ulong_extras.h"
16 #include "fmpz.h"
17 
fmpz_fdiv_r_2exp(fmpz_t f,const fmpz_t g,ulong exp)18 void fmpz_fdiv_r_2exp(fmpz_t f, const fmpz_t g, ulong exp)
19 {
20     fmpz d = *g;
21 
22     if (!COEFF_IS_MPZ(d))  /* g is small */
23     {
24         if (d >= 0)
25         {
26             fmpz_set_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_set_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             }
42         }
43     }
44     else  /*g is large */
45     {
46         __mpz_struct * mpz_ptr = _fmpz_promote(f);  /* g is already large */
47         mpz_fdiv_r_2exp(mpz_ptr, COEFF_TO_PTR(d), exp);
48         _fmpz_demote_val(f);  /* division may make value small */
49     }
50 }
51 
52