1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
Copyright (C) 2012 Fredrik Johansson
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 3 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/
#include <gmp.h>
#include "longlong.h"
#include "fmpz.h"
ulong
fmpz_abs_ubound_ui_2exp(slong * exp, const fmpz_t x, int bits)
{
ulong m;
slong shift, e, size;
fmpz c = *x;
if (!COEFF_IS_MPZ(c))
{
m = FLINT_ABS(c);
e = 0;
}
else
{
/* mpz */
mpz_ptr z = COEFF_TO_PTR(c);
size = z->_mp_size;
size = FLINT_ABS(size);
e = (size - 1) * FLINT_BITS;
if (size == 1)
{
m = z->_mp_d[0];
}
else /* there are two or more limbs */
{
/* top limb (which must be nonzero) */
m = z->_mp_d[size - 1];
shift = flint_clz(m);
shift = FLINT_BITS - shift - bits;
e += shift;
if (shift >= 0)
{
/* round up */
m = (m >> shift) + 1;
}
else
{
/* read a second limb to get an accurate value */
ulong m2 = z->_mp_d[size - 2];
m = (m << (-shift)) | (m2 >> (FLINT_BITS + shift));
/* round up */
m++;
}
/* adding 1 caused overflow to the next power of two */
if ((m & (m - UWORD(1))) == UWORD(0))
{
m = UWORD(1) << (bits - 1);
e++;
}
*exp = e;
return m;
}
}
/* single limb, adjust */
shift = flint_clz(m);
e = FLINT_BITS - shift - bits;
if (e >= 0)
{
m = (m >> e) + 1;
/* overflowed to next power of two */
if ((m & (m - 1)) == UWORD(0))
{
m = UWORD(1) << (bits - 1);
e++;
}
}
else
{
m <<= (-e);
}
*exp = e;
return m;
}