fmpz.h – integers¶
By default, an fmpz_t
is implemented as an array of
fmpz
’s of length one to allow passing by reference as one can
do with GMP’s mpz_t
type. The fmpz_t
type is
simply a single limb, though the user does not need to be aware of
this except in one specific case outlined below.
In all respects, fmpz_t
’s act precisely like GMP’s
mpz_t
’s, with automatic memory management, however, in the first
place only one limb is used to implement them. Once an fmpz_t
overflows a limb then a multiprecision integer is automatically
allocated and instead of storing the actual integer data the
slong
which implements the type becomes an index into a FLINT
wide array of mpz_t
’s.
These internal implementation details are not important for the user to understand, except for three important things.
Firstly, fmpz_t
’s will be more efficient than mpz_t
’s
for single limb operations, or more precisely for signed quantities
whose absolute value does not exceed FLINT_BITS - 2`
bits.
Secondly, for small integers that fit into `FLINT_BITS - 2`
bits
much less memory will be used than for an mpz_t
. When very
many fmpz_t
’s are used, there can be important cache benefits
on account of this.
Thirdly, it is important to understand how to deal with arrays of
fmpz_t
’s. As for mpz_t
’s, there is an underlying type,
an fmpz
, which can be used to create the array, e.g.
fmpz myarr[100];
Now recall that an fmpz_t
is an array of length one of
fmpz
’s. Thus, a pointer to an fmpz
can be used in
place of an fmpz_t
. For example, to find the sign of the third
integer in our array we would write
int sign = fmpz_sgn(myarr + 2);
The fmpz
module provides routines for memory management, basic
manipulation and basic arithmetic.
Unless otherwise specified, all functions in this section permit aliasing between their input arguments and between their input and output arguments.
Simple example¶
The following example computes the square of the integer
#include "fmpz.h"
int main()
{
fmpz_t x, y;
fmpz_init(x);
fmpz_init(y);
fmpz_set_ui(x, 7);
fmpz_mul(y, x, x);
fmpz_print(x);
flint_printf("^2 = ");
fmpz_print(y);
flint_printf("\n");
fmpz_clear(x);
fmpz_clear(y);
}
7^2 = 49
Types, macros and constants¶
-
type fmpz¶
The FLINT multi-precision integer type uses an inline representation for small integers, specifically when the absolute value is at most
(on 64-bit machines) or (on 32-bit machines). It switches automatically to a GMP integer for larger values.An
fmpz
is implemented as anslong
. When its second most significant bit is thefmpz
represents an ordinaryslong
integer whose absolute value is at mostFLINT_BITS - 2
bits.When the second most significant bit is
then the value represents a pointer (the pointer is shifted right bits and the second most significant bit is set to . This relies on the fact thatmalloc
always allocates memory blocks on a or byte boundary).
-
type fmpz_t¶
An array of length 1 of
fmpz
’s. This is used to passfmpz
’s around by reference without fuss, similar to the waympz_t
works.
-
COEFF_MAX¶
The largest (positive) value an
fmpz
can be if just anslong
.
-
COEFF_MIN¶
The smallest (negative) value an
fmpz
can be if just anslong
.
-
fmpz PTR_TO_COEFF(mpz_ptr ptr)¶
A macro to convert an
mpz_t
(or more generally anympz_ptr
) to anfmpz
(shifts the pointer right by and sets the second most significant bit).
-
mpz_ptr COEFF_TO_PTR(fmpz f)¶
A macro to convert an
fmpz
which represents a pointer into an actual pointer to an__mpz_struct
(i.e. to anmpz_t
).
-
COEFF_IS_MPZ(f)¶
A macro which returns
if represents anmpz_t
, otherwise is returned.
-
MPZ_MIN_ALLOC¶
A constant determining the minimum number of limbs the fmpz memory manager will allocate for each mpz. This constant is currently 2.
-
mpz_ptr _fmpz_new_mpz(void)¶
Returns a pointer to an initialised mpz with at least
MPZ_MIN_ALLOC
limbs allocated. This is only used internally.Note: Requires that
gmp.h
has been included before any FLINT header is included.
-
void _fmpz_clear_mpz(fmpz f)¶
Clears the mpz “pointed to” by the fmpz f. This is only used internally.
Note
As of FLINT 3.2.0, it is required that the mpz pointed to by f has at
least MPZ_MIN_ALLOC
limbs allocated when _fmpz_clear_mpz()
is
called. Note that GMP functions never reduce the number of allocated limbs,
apart from a bug in mpz_remove
which as of GMP 6.3.0 may reduce the
number of allocated limbs in the output mpz. Hence, as long as
mpz_realloc
never is called with a second argument less than
MPZ_MIN_ALLOC
on an mpz received from _fmpz_new_mpz()
, any
other usage should be fine.
-
void _fmpz_cleanup_mpz_content()¶
This function does nothing in the reentrant version of
fmpz
.
-
void _fmpz_cleanup()¶
This function does nothing in the reentrant version of
fmpz
.
-
mpz_ptr _fmpz_promote(fmpz_t f)¶
If
doesn’t represent anmpz_t
, initialise one and associate it to .Note: Requires that
gmp.h
has been included before any FLINT header is included.
-
mpz_ptr _fmpz_promote_val(fmpz_t f)¶
If
doesn’t represent anmpz_t
, initialise one and associate it to , but preserve the value of .This function is for internal use. The resulting
fmpz
will be backed by anmpz_t
that can be passed to GMP, but thefmpz
will be in an inconsistent state with respect to the other FLINTfmpz
functions such asfmpz_is_zero
, etc.Note: Requires that
gmp.h
has been included before any FLINT header is included.
Memory management¶
-
void fmpz_init(fmpz_t f)¶
A small
fmpz_t
is initialised, i.e. just aslong
. The value is set to zero.
-
void fmpz_init2(fmpz_t f, ulong limbs)¶
Initialises the given
fmpz_t
to have space for the given number of limbs.If
limbs
is zero then a smallfmpz_t
is allocated, i.e. just aslong
. The value is also set to zero. It is not necessary to call this function except to save time. A call tofmpz_init
will do just fine.
Random generation¶
For thread-safety, the randomisation methods take as one of their parameters an
object of type flint_rand_t
. Before calling any of the randomisation
functions such an object first has to be initialised with a call to
flint_rand_init()
. When one is finished generating random numbers, one
should call flint_rand_clear()
to clean up.
-
void fmpz_randbits_unsigned(fmpz_t f, flint_rand_t state, flint_bitcnt_t bits)¶
-
void fmpz_randbits(fmpz_t f, flint_rand_t state, flint_bitcnt_t bits)¶
Generates a random integer whose absolute value has precisely the given number of bits.
-
void fmpz_randtest_unsigned(fmpz_t f, flint_rand_t state, flint_bitcnt_t bits)¶
-
void fmpz_randtest(fmpz_t f, flint_rand_t state, flint_bitcnt_t bits)¶
Generates a random integer whose absolute value has a number of bits which is random from
up tobits
inclusive.
-
void fmpz_randtest_not_zero(fmpz_t f, flint_rand_t state, flint_bitcnt_t bits)¶
As per
fmpz_randtest
, but the result will not be . Ifbits
is set to , an exception will result.
-
void fmpz_randm(fmpz_t f, flint_rand_t state, const fmpz_t m)¶
Generates a random integer in the range
to inclusive.
-
void fmpz_randtest_mod(fmpz_t f, flint_rand_t state, const fmpz_t m)¶
Generates a random integer in the range
to inclusive, with an increased probability of generating values close to the endpoints.
-
void fmpz_randtest_mod_signed(fmpz_t f, flint_rand_t state, const fmpz_t m)¶
Generates a random integer in the range
, with an increased probability of generating values close to the endpoints or close to zero.
-
void fmpz_randprime(fmpz_t f, flint_rand_t state, flint_bitcnt_t bits, int proved)¶
Generates a random prime number with the given number of bits.
The generation is performed by choosing a random number and then finding the next largest prime, and therefore does not quite give a uniform distribution over the set of primes with that many bits.
Random number generation is performed using the standard FLINT random number generator, which is not suitable for cryptographic use.
If
proved
is nonzero, then the integer returned is guaranteed to actually be prime.
Conversion¶
-
slong fmpz_get_si(const fmpz_t f)¶
Returns
as aslong
. The result is undefined if does not fit into aslong
.
-
ulong fmpz_get_ui(const fmpz_t f)¶
Returns
as anulong
. The result is undefined if does not fit into anulong
or is negative.
-
void fmpz_get_uiui(ulong *hi, ulong *low, const fmpz_t f)¶
If
consists of two limbs, then*hi
and*low
are set to the high and low limbs, otherwise*low
is set to the low limb and*hi
is set to .
-
double fmpz_get_d(const fmpz_t f)¶
Returns
as adouble
, rounding down towards zero if cannot be represented exactly. The outcome is undefined if is too large to fit in the normal range of a double.
-
void fmpz_set_mpf(fmpz_t f, const mpf_t x)¶
Sets
to thempf_t
, rounding down towards zero if the value of is fractional.Note: Requires that
gmp.h
has been included before any FLINT header is included.
-
void fmpz_get_mpf(mpf_t x, const fmpz_t f)¶
Sets the value of the
mpf_t
to the value of .Note: Requires that
gmp.h
has been included before any FLINT header is included.
-
void fmpz_get_mpfr(mpfr_t x, const fmpz_t f, mpfr_rnd_t rnd)¶
Sets the value of
from , rounded toward the given directionrnd
.Note: Requires that
mpfr.h
has been included before any FLINT header is included.
-
double fmpz_get_d_2exp(slong *exp, const fmpz_t f)¶
Returns
as a normalizeddouble
along with a -exponentexp
, i.e. if is the return value then , to within 1 ULP.
-
void fmpz_get_mpz(mpz_t x, const fmpz_t f)¶
Sets the
mpz_t
to the same value as .Note: Requires that
gmp.h
has been included before any FLINT header is included.
-
int fmpz_get_mpn(nn_ptr *n, fmpz_t n_in)¶
Sets the
nn_ptr
to the same value as . Returned integer is number of limbs allocated to , minimum number of limbs required to hold the value stored in .
-
char *fmpz_get_str(char *str, int b, const fmpz_t f)¶
Returns the representation of
in base , which can vary between and , inclusive.If
str
isNULL
, the result string is allocated by the function. Otherwise, it is up to the caller to ensure that the allocated block of memory is sufficiently large.
-
void fmpz_set_d(fmpz_t f, double c)¶
Sets
to thedouble
, rounding down towards zero if the value of is fractional. The outcome is undefined if is infinite, not-a-number, or subnormal.
-
void fmpz_set_uiui(fmpz_t f, ulong hi, ulong lo)¶
Sets
tolo
, plushi
shifted to the left byFLINT_BITS
.
-
void fmpz_neg_uiui(fmpz_t f, ulong hi, ulong lo)¶
Sets
tolo
, plushi
shifted to the left byFLINT_BITS
, and then negates .
-
void fmpz_set_signed_uiui(fmpz_t f, ulong hi, ulong lo)¶
Sets
tolo
, plushi
shifted to the left byFLINT_BITS
, interpreted as a signed two’s complement integer with2 * FLINT_BITS
bits.
-
void fmpz_set_signed_uiuiui(fmpz_t f, ulong hi, ulong mid, ulong lo)¶
Sets
tolo
, plusmid
shifted to the left byFLINT_BITS
, plushi
shifted to the left by2*FLINT_BITS
bits, interpreted as a signed two’s complement integer with3 * FLINT_BITS
bits.
-
void fmpz_set_ui_array(fmpz_t out, const ulong *in, slong n)¶
Sets
out
to the nonnegative integerin[0] + in[1]*X + ... + in[n - 1]*X^(n - 1)
whereX = 2^FLINT_BITS
. It is assumed thatn > 0
.
-
void fmpz_set_signed_ui_array(fmpz_t out, const ulong *in, slong n)¶
Sets
out
to the integer represented inin[0], ..., in[n - 1]
as a signed two’s complement integer withn * FLINT_BITS
bits. It is assumed thatn > 0
. The function operates as a call tofmpz_set_ui_array()
followed by a symmetric remainder modulo .
-
void fmpz_get_ui_array(ulong *out, slong n, const fmpz_t in)¶
Assuming that the nonnegative integer
in
can be represented in the formout[0] + out[1]*X + ... + out[n - 1]*X^(n - 1)
, where , sets the corresponding elements ofout
so that this is true. It is assumed thatn > 0
.
-
void fmpz_get_signed_ui_array(ulong *out, slong n, const fmpz_t in)¶
Retrieves the value of
modulo and puts the words of the result inout[0], ..., out[n-1]
. This will give a signed two’s complement representation of (assuming doesn’t overflow the array).
-
void fmpz_set_mpn_large(fmpz_t z, nn_srcptr src, slong n, int negative)¶
Sets z to the integer represented by the n limbs in the array src, or minus this value if negative is 1. Requires
and that the top limb of src is nonzero. Note that fmpz_set_ui, fmpz_neg_ui can be used for single-limb integers.
-
void fmpz_get_signed_uiui(ulong *hi, ulong *lo, const fmpz_t in)¶
Retrieves the value of
modulo and puts the high and low words into*hi
and*lo
respectively.
-
void fmpz_set_mpz(fmpz_t f, const mpz_t x)¶
Sets
to the givenmpz_t
value.Note: Requires that
gmp.h
has been included before any FLINT header is included.
-
int fmpz_set_str(fmpz_t f, const char *str, int b)¶
Sets
to the value given in the null-terminated stringstr
, in base . The base can vary between and , inclusive. Returns if the string contains a valid input and otherwise.
-
void fmpz_set_ui_smod(fmpz_t f, ulong x, ulong m)¶
Sets
to the signed remainder satisfying , given which is assumed to satisfy .
-
void flint_mpz_init_set_readonly(mpz_t z, const fmpz_t f)¶
Sets the uninitialised
mpz_t
to the value of the readonlyfmpz_t
.Note that it is assumed that
does not change during the lifetime of .The integer
has to be cleared by a call toflint_mpz_clear_readonly()
.The suggested use of the two functions is as follows:
fmpz_t f; ... { mpz_t z; flint_mpz_init_set_readonly(z, f); foo(..., z); flint_mpz_clear_readonly(z); }
This provides a convenient function for user code, only requiring to work with the types
fmpz_t
andmpz_t
.In critical code, the following approach may be favourable:
fmpz_t f; ... { mpz_ptr z; z = _fmpz_promote_val(f); foo(..., z); _fmpz_demote_val(f); }
Note: Requires that
gmp.h
has been included before any FLINT header is included.
-
void flint_mpz_clear_readonly(mpz_t z)¶
Clears the readonly
mpz_t
.Note: Requires that
gmp.h
has been included before any FLINT header is included.
-
void fmpz_init_set_readonly(fmpz_t f, const mpz_t z)¶
Sets the uninitialised
fmpz_t
to a readonly version of the integer .Note that the value of
is assumed to remain constant throughout the lifetime of .The
fmpz_t
has to be cleared by calling the functionfmpz_clear_readonly()
.The suggested use of the two functions is as follows:
mpz_t z; ... { fmpz_t f; fmpz_init_set_readonly(f, z); foo(..., f); fmpz_clear_readonly(f); }
Note: Requires that
gmp.h
has been included before any FLINT header is included.
Input and output¶
-
int fmpz_read(fmpz_t f)¶
Reads a multiprecision integer from
stdin
. The format is an optional minus sign, followed by one or more digits. The first digit should be non-zero unless it is the only digit.In case of success, returns a positive number. In case of failure, returns a non-positive number.
This convention is adopted in light of the return values of
scanf
from the standard library andmpz_inp_str
from GMP.
-
int fmpz_fread(FILE *file, fmpz_t f)¶
Reads a multiprecision integer from the stream
file
. The format is an optional minus sign, followed by one or more digits. The first digit should be non-zero unless it is the only digit.In case of success, returns a positive number. In case of failure, returns a non-positive number.
This convention is adopted in light of the return values of
scanf
from the standard library andmpz_inp_str
from GMP.
-
size_t fmpz_inp_raw(fmpz_t x, FILE *fin)¶
Reads a multiprecision integer from the stream
file
. The format is raw binary format write byfmpz_out_raw()
.In case of success, return a positive number, indicating number of bytes read. In case of failure 0.
This function calls the
mpz_inp_raw
function in library gmp. So that it can read the raw data written bympz_inp_raw
directly.
-
int fmpz_fprint(FILE *fs, const fmpz_t x)¶
-
int fmpz_print(const fmpz_t x)¶
Prints the value
tofs
orstdout
, without a carriage return. The value is printed as either , the decimal digits of a positive integer, or a minus sign followed by the digits of a negative integer.Returns the number of characters written to file stream.
-
size_t fmpz_out_raw(FILE *fout, const fmpz_t x)¶
Writes the value
tofile
. The value is written in raw binary format. The integer is written in portable format, with 4 bytes of size information, and that many bytes of limbs. Both the size and the limbs are written in decreasing significance order (i.e., in big-endian).The output can be read with
fmpz_inp_raw
.In case of success, return a positive number, indicating number of bytes written. In case of failure, return 0.
The output of this can also be read by
mpz_inp_raw
from GMP, since this function calls thempz_inp_raw
function in library gmp.
Basic properties and manipulation¶
-
size_t fmpz_sizeinbase(const fmpz_t f, int b)¶
Returns the size of the absolute value of
in base , measured in numbers of digits. The base can be between and , inclusive.
-
flint_bitcnt_t fmpz_bits(const fmpz_t f)¶
Returns the number of bits required to store the absolute value of
. If is then is returned.
-
slong fmpz_size(const fmpz_t f)¶
Returns the number of limbs required to store the absolute value of
. If is zero then is returned.
-
int fmpz_sgn(const fmpz_t f)¶
Returns
if the sign of is negative, if it is positive, otherwise returns .
-
flint_bitcnt_t fmpz_val2(const fmpz_t f)¶
Returns the exponent of the largest power of two dividing
, or equivalently the number of trailing zeros in the binary expansion of . If is zero then is returned.
-
ulong fmpz_abs_lbound_ui_2exp(slong *exp, const fmpz_t x, int bits)¶
For nonzero
, returns a mantissa with exactlybits
bits and setsexp
to an exponent , such that . The number of bits must be between 1 andFLINT_BITS
inclusive. The mantissa is guaranteed to be correctly rounded.
-
ulong fmpz_abs_ubound_ui_2exp(slong *exp, const fmpz_t x, int bits)¶
For nonzero
, returns a mantissa with exactlybits
bits and setsexp
to an exponent , such that . The number of bits must be between 1 andFLINT_BITS
inclusive. The mantissa is either correctly rounded or one unit too large (possibly meaning that the exponent is one too large, if the mantissa is a power of two).
Comparison¶
-
int fmpz_cmp_si(const fmpz_t f, slong g)¶
Returns a negative value if
, positive value if , otherwise returns .
-
int fmpz_cmpabs(const fmpz_t f, const fmpz_t g)¶
Returns a negative value if
, positive value if , otherwise returns .
Basic arithmetic¶
-
void fmpz_add(fmpz_t f, const fmpz_t g, const fmpz_t h)¶
-
void fmpz_add_ui(fmpz_t f, const fmpz_t g, ulong h)¶
-
void fmpz_add_si(fmpz_t f, const fmpz_t g, slong h)¶
Sets
to .
-
void fmpz_sub(fmpz_t f, const fmpz_t g, const fmpz_t h)¶
-
void fmpz_sub_ui(fmpz_t f, const fmpz_t g, ulong h)¶
-
void fmpz_sub_si(fmpz_t f, const fmpz_t g, slong h)¶
Sets
to .
-
void fmpz_mul(fmpz_t f, const fmpz_t g, const fmpz_t h)¶
-
void fmpz_mul_ui(fmpz_t f, const fmpz_t g, ulong h)¶
-
void fmpz_mul_si(fmpz_t f, const fmpz_t g, slong h)¶
Sets
to .
-
void fmpz_mul2_uiui(fmpz_t f, const fmpz_t g, ulong x, ulong y)¶
Sets
to where and are of typeulong
.
-
void fmpz_mul_2exp(fmpz_t f, const fmpz_t g, ulong e)¶
Sets
to .Note: Assumes that
e + FLINT_BITS
does not overflow.
-
void fmpz_addmul(fmpz_t f, const fmpz_t g, const fmpz_t h)¶
-
void fmpz_addmul_ui(fmpz_t f, const fmpz_t g, ulong h)¶
-
void fmpz_addmul_si(fmpz_t f, const fmpz_t g, slong h)¶
Sets
to .
-
void fmpz_submul(fmpz_t f, const fmpz_t g, const fmpz_t h)¶
-
void fmpz_submul_ui(fmpz_t f, const fmpz_t g, ulong h)¶
-
void fmpz_submul_si(fmpz_t f, const fmpz_t g, slong h)¶
Sets
to .
-
void fmpz_tdiv_r_2exp(fmpz_t s, const fmpz_t g, ulong exp)¶
Sets
to the quotient of by and/or to the remainder. For the2exp
functions,g = 2^exp
. is an exception is raised.Rounding is made in the following way:
fdiv
rounds the quotient via floor rounding.cdiv
rounds the quotient via ceil rounding.tdiv
rounds the quotient via truncation, i.e. rounding towards zero.ndiv
rounds the quotient such that the remainder has the smallest absolute value. In case of ties, it rounds the quotient towards zero.
-
ulong fmpz_tdiv_ui(const fmpz_t g, ulong h)¶
Returns the absolute value remainder of
divided by , following the convention of rounding as seen above. If is zero an exception is raised.
-
void fmpz_divexact_ui(fmpz_t f, const fmpz_t g, ulong h)¶
Sets
to the quotient of and , assuming that the division is exact, i.e. is a multiple of . If is an exception is raised.
-
void fmpz_divexact2_uiui(fmpz_t f, const fmpz_t g, ulong x, ulong y)¶
Sets
to the quotient of and , assuming that the division is exact, i.e. is a multiple of . If or is an exception is raised.
-
int fmpz_divisible_si(const fmpz_t f, slong g)¶
Returns
if there is an integer with and if there is none.
-
int fmpz_divides(fmpz_t q, const fmpz_t f, const fmpz_t g)¶
Returns
if there is an integer with and sets to the quotient. Otherwise returns and sets to .
-
void fmpz_mod(fmpz_t f, const fmpz_t g, const fmpz_t h)¶
Sets
to the remainder of divided by such that the remainder is non-negative. Assumes that is not zero.
-
ulong fmpz_mod_ui(fmpz_t f, const fmpz_t g, ulong h)¶
Sets
to the remainder of divided by such that the remainder is non-negative and also returns this value. Raises an exception if is zero.
-
void fmpz_preinvn_init(fmpz_preinvn_t inv, const fmpz_t f)¶
Compute a precomputed inverse
inv
off
for use in thepreinvn
functions listed below.
-
void fmpz_preinvn_clear(fmpz_preinvn_t inv)¶
Clean up the resources used by a precomputed inverse created with the
fmpz_preinvn_init()
function.
-
void fmpz_fdiv_qr_preinvn(fmpz_t f, fmpz_t s, const fmpz_t g, const fmpz_t h, const fmpz_preinvn_t hinv)¶
As per
fmpz_fdiv_qr()
, but takes a precomputed inversehinv
of constructed usingfmpz_preinvn()
.This function will be faster than
fmpz_fdiv_qr_preinvn()
when the number of limbs of is at leastPREINVN_CUTOFF
.
-
void fmpz_pow_ui(fmpz_t f, const fmpz_t g, ulong x)¶
-
void fmpz_ui_pow_ui(fmpz_t f, ulong g, ulong x)¶
Sets
to . Defines .
-
int fmpz_pow_fmpz(fmpz_t f, const fmpz_t g, const fmpz_t x)¶
Sets
to . Defines . Return for success and for failure. The function throws only if is negative.
-
void fmpz_powm(fmpz_t f, const fmpz_t g, const fmpz_t e, const fmpz_t m)¶
Sets
to . If , sets to .Assumes that
, raises anabort
signal otherwise.
-
slong fmpz_clog(const fmpz_t x, const fmpz_t b)¶
-
slong fmpz_clog_ui(const fmpz_t x, ulong b)¶
Returns
.Assumes that
and and that the return value fits into a signedslong
.
-
slong fmpz_flog(const fmpz_t x, const fmpz_t b)¶
-
slong fmpz_flog_ui(const fmpz_t x, ulong b)¶
Returns
.Assumes that
and and that the return value fits into a signedslong
.
-
double fmpz_dlog(const fmpz_t x)¶
Returns a double precision approximation of the natural logarithm of
.The accuracy depends on the implementation of the floating-point logarithm provided by the C standard library. The result can typically be expected to have a relative error no greater than 1-2 bits.
-
int fmpz_sqrtmod(fmpz_t b, const fmpz_t a, const fmpz_t p)¶
If
is prime, set to a square root of modulo if is a quadratic residue modulo and return , otherwise return .If
is not prime the return value is with high probability , indicating that is not prime, or is not a square modulo . If is not prime and the return value is , the value of is meaningless.
-
void fmpz_sqrt(fmpz_t f, const fmpz_t g)¶
Sets
to the integer part of the square root of , where is assumed to be non-negative. If is negative, an exception is raised.
-
void fmpz_sqrtrem(fmpz_t f, fmpz_t r, const fmpz_t g)¶
Sets
to the integer part of the square root of , where is assumed to be non-negative, and sets to the remainder, that is, the difference . If is negative, an exception is raised. The behaviour is undefined if and are aliases.
-
int fmpz_root(fmpz_t r, const fmpz_t f, slong n)¶
Set
to the integer part of the -th root of . Requires that and that if is even then be non-negative, otherwise an exception is raised. The function returns if the root was exact, otherwise .
-
int fmpz_is_perfect_power(fmpz_t root, const fmpz_t f)¶
If
is a perfect power setroot
to and return , otherwise return . Note that are all considered perfect powers. No guarantee is made about or being the smallest possible value. Negative values of are permitted.
-
void _fmpz_rfac_ui(fmpz_t r, const fmpz_t x, ulong a, ulong b)¶
Sets
to the rising factorial . Assumes .
Greatest common divisor¶
-
void fmpz_gcd(fmpz_t f, const fmpz_t g, const fmpz_t h)¶
Sets
to the greatest common divisor of and . The result is always non-negative, even if one of and is negative.
-
void fmpz_gcd3(fmpz_t f, const fmpz_t a, const fmpz_t b, const fmpz_t c)¶
Sets
to the greatest common divisor of , and . This is equivalent to callingfmpz_gcd
twice, but may be faster.
-
void fmpz_lcm(fmpz_t f, const fmpz_t g, const fmpz_t h)¶
Sets
to the least common multiple of and . The result is always nonnegative, even if one of and is negative.
-
void fmpz_gcdinv(fmpz_t d, fmpz_t a, const fmpz_t f, const fmpz_t g)¶
Given integers
with , computes the greatest common divisor and the modular inverse , whenever .Assumes that
and are not aliased.
-
void fmpz_xgcd(fmpz_t d, fmpz_t a, fmpz_t b, const fmpz_t f, const fmpz_t g)¶
Computes the extended GCD of
and , i.e. the values and such that , where . Here will be the same as callingfmpz_gcdinv
when (or vice versa for when ).To obtain the canonical solution to Bézout’s identity, call
fmpz_xgcd_canonical_bezout
instead. This is also faster.Assumes that there is no aliasing among the outputs.
-
void fmpz_xgcd_canonical_bezout(fmpz_t d, fmpz_t a, fmpz_t b, const fmpz_t f, const fmpz_t g)¶
Computes the extended GCD
such that the solution is the canonical solution to Bézout’s identity. We define the canonical solution to satisfy one of the following if one of the given conditions apply:If the pair
does not satisfy any of these conditions, the solution will satisfy the following:Assumes that there is no aliasing among the outputs.
-
void fmpz_xgcd_partial(fmpz_t co2, fmpz_t co1, fmpz_t r2, fmpz_t r1, const fmpz_t L)¶
This function is an implementation of Lehmer extended GCD with early termination, as used in the
qfb
module. It terminates early when remainders fall below the specified bound. The initial valuesr1
andr2
are treated as successive remainders in the Euclidean algorithm and are replaced with the last two remainders computed. The valuesco1
andco2
are the last two cofactors and satisfy the identityco2*r1 - co1*r2 == +/- r2_orig
upon termination, wherer2_orig
is the starting value ofr2
supplied, andr1
andr2
are the final values.Aliasing of inputs is not allowed. Similarly aliasing of inputs and outputs is not allowed.
Modular arithmetic¶
-
slong _fmpz_remove(fmpz_t x, const fmpz_t f, double finv)¶
Removes all factors
from and returns the number of such.Assumes that
is non-zero, that and thatfinv
is the precomputeddouble
inverse of whenever is a small integer and otherwise.Does not support aliasing.
-
slong fmpz_remove(fmpz_t rop, const fmpz_t op, const fmpz_t f)¶
Remove all occurrences of the factor
from the integerop
and setsrop
to the resulting integer.If
op
is zero, setsrop
toop
and returns .Returns an
abort
signal if any of the assumptions are violated.
-
int fmpz_invmod(fmpz_t f, const fmpz_t g, const fmpz_t h)¶
Sets
to the inverse of modulo . The value of may not be otherwise an exception results. If the inverse exists the return value will be non-zero, otherwise the return value will be and the value of undefined. As a special case, we consider any number invertible modulo , with inverse 0.
-
int fmpz_jacobi(const fmpz_t a, const fmpz_t n)¶
Computes the Jacobi symbol
for any and odd positive .
-
void fmpz_divides_mod_list(fmpz_t xstart, fmpz_t xstride, fmpz_t xlength, const fmpz_t a, const fmpz_t b, const fmpz_t n)¶
Set
, , and so that the solution set for modulo in is exactly . This function essentially gives a list of possibilities for the fraction modulo . The outputs may not be aliased, and should be positive.
Bit packing and unpacking¶
-
int fmpz_bit_pack(ulong *arr, flint_bitcnt_t shift, flint_bitcnt_t bits, const fmpz_t coeff, int negate, int borrow)¶
Shifts the given coefficient to the left by
shift
bits and adds it to the integer inarr
in a field of the given number of bits:shift bits -------------- X X X C C C C 0 0 0 0 0 0 0
An optional borrow of
can be subtracted fromcoeff
before it is packed. Ifcoeff
is negative after the borrow, then a borrow will be returned by the function.The value of
shift
is assumed to be less thanFLINT_BITS
. All but the firstshift
bits ofarr
are assumed to be zero on entry to the function.The value of
coeff
may also be optionally (and notionally) negated before it is used, by setting thenegate
parameter to .
-
int fmpz_bit_unpack(fmpz_t coeff, ulong *arr, flint_bitcnt_t shift, flint_bitcnt_t bits, int negate, int borrow)¶
A bit field of the given number of bits is extracted from
arr
, starting aftershift
bits, and placed intocoeff
. An optional borrow of may be added to the coefficient. If the result is negative, a borrow of is returned. Finally, the resultingcoeff
may be negated by setting thenegate
parameter to .The value of
shift
is expected to be less thanFLINT_BITS
.
-
void fmpz_bit_unpack_unsigned(fmpz_t coeff, const ulong *arr, flint_bitcnt_t shift, flint_bitcnt_t bits)¶
A bit field of the given number of bits is extracted from
arr
, starting aftershift
bits, and placed intocoeff
.The value of
shift
is expected to be less thanFLINT_BITS
.
Logic Operations¶
-
void fmpz_and(fmpz_t r, const fmpz_t a, const fmpz_t b)¶
Sets
r
to the bit-wise logicaland
ofa
andb
.
-
void fmpz_or(fmpz_t r, const fmpz_t a, const fmpz_t b)¶
Sets
r
to the bit-wise logical (inclusive)or
ofa
andb
.
Chinese remaindering¶
The following functions can be used to reconstruct an integer from its
residues modulo a set of prime numbers. The first two
functions, fmpz_CRT_ui()
and fmpz_CRT()
, are easy
to use and allow building the result one residue at a time, which is
useful when the number of needed primes is not known in advance.
The remaining functions support performing the modular reductions and
reconstruction using balanced subdivision. This greatly improves
efficiency for large integers but assumes that the basis of primes is
known in advance. The user must precompute a comb
structure and temporary working space with fmpz_comb_init()
and
fmpz_comb_temp_init()
, and free this data afterwards.
For simple demonstration programs showing how to use the CRT functions,
see crt.c
and multi_crt.c
in the examples
directory.
The fmpz_multi_CRT
class is similar to fmpz_multi_CRT_ui
except that it performs error checking and works with arbitrary moduli.
-
void fmpz_CRT_ui(fmpz_t out, const fmpz_t r1, const fmpz_t m1, ulong r2, ulong m2, int sign)¶
Uses the Chinese Remainder Theorem to compute the unique integer
(if sign = 0) or (if sign = 1) congruent to modulo and modulo , where . The result is stored inout
.It is assumed that
and are positive coprime integers.If sign = 0, it is assumed that
and . Otherwise, it is assumed that and .
-
void fmpz_CRT(fmpz_t out, const fmpz_t r1, const fmpz_t m1, const fmpz_t r2, const fmpz_t m2, int sign)¶
Use the Chinese Remainder Theorem to set
out
to the unique value (if sign = 0) or (if sign = 1) congruent to modulo and modulo , where .It is assumed that
and are positive coprime integers.If sign = 0, it is assumed that
and . Otherwise, it is assumed that and .
-
void fmpz_multi_mod_ui(ulong *out, const fmpz_t in, const fmpz_comb_t comb, fmpz_comb_temp_t temp)¶
Reduces the multiprecision integer
in
modulo each of the primes stored in thecomb
structure. The arrayout
will be filled with the residues modulo these primes. The structuretemp
is temporary space which must be provided byfmpz_comb_temp_init()
and cleared byfmpz_comb_temp_clear()
.
-
void fmpz_multi_CRT_ui(fmpz_t output, nn_srcptr residues, const fmpz_comb_t comb, fmpz_comb_temp_t ctemp, int sign)¶
This function takes a set of residues modulo the list of primes contained in the
comb
structure and reconstructs a multiprecision integer modulo the product of the primes which has these residues modulo the corresponding primes.If
is the product of all the primes thenout
is normalised to be in the range if sign = 0 and the range if sign = 1. The arraytemp
is temporary space which must be provided byfmpz_comb_temp_init()
and cleared byfmpz_comb_temp_clear()
.
-
void fmpz_comb_init(fmpz_comb_t comb, nn_srcptr primes, slong num_primes)¶
Initialises a
comb
structure for multimodular reduction and recombination. The arrayprimes
is assumed to containnum_primes
primes each ofFLINT_BITS - 1
bits. Modular reductions and recombinations will be done modulo this list of primes. Theprimes
array must not befree
’d until thecomb
structure is no longer required and must be cleared by the user.
-
void fmpz_comb_temp_init(fmpz_comb_temp_t temp, const fmpz_comb_t comb)¶
Creates temporary space to be used by multimodular and CRT functions based on an initialised
comb
structure.
-
void fmpz_comb_clear(fmpz_comb_t comb)¶
Clears the given
comb
structure, releasing any memory it uses.
-
void fmpz_comb_temp_clear(fmpz_comb_temp_t temp)¶
Clears temporary space
temp
used by multimodular and CRT functions using the givencomb
structure.
-
void fmpz_multi_CRT_init(fmpz_multi_CRT_t CRT)¶
Initialize
CRT
for Chinese remaindering.
-
int fmpz_multi_CRT_precompute(fmpz_multi_CRT_t CRT, const fmpz *moduli, slong len)¶
Configure
CRT
for repeated Chinese remaindering ofmoduli
. The number of moduli,len
, should be positive. A return of0
indicates that the compilation failed and future calls tofmpz_multi_CRT_precomp()
will leave the output undefined. A return of1
indicates that the compilation was successful, which occurs if and only if either (1)len == 1
andmodulus + 0
is nonzero, or (2) no modulus is and all moduli are pairwise relatively prime.
-
void fmpz_multi_CRT_precomp(fmpz_t output, const fmpz_multi_CRT_t P, const fmpz *inputs, int sign)¶
Set
output
to an integer of smallest absolute value that is congruent tovalues + i
modulo themoduli + i
inP
.
-
int fmpz_multi_CRT(fmpz_t output, const fmpz *moduli, const fmpz *values, slong len, int sign)¶
Perform the same operation as
fmpz_multi_CRT_precomp()
while internally constructing and destroying the precomputed data. All of the remarks infmpz_multi_CRT_precompute()
apply.
-
void fmpz_multi_CRT_clear(fmpz_multi_CRT_t P)¶
Free all space used by
CRT
.
Primality testing¶
-
int fmpz_is_strong_probabprime(const fmpz_t n, const fmpz_t a)¶
Returns
if is a strong probable prime to base , otherwise it returns .
-
int fmpz_is_probabprime_lucas(const fmpz_t n)¶
Performs a Lucas probable prime test with parameters chosen by Selfridge’s method
as per [BaiWag1980].Return
if is a Lucas probable prime, otherwise return . This function declares some composites probably prime, but no primes composite.
-
int fmpz_is_probabprime_BPSW(const fmpz_t n)¶
Perform a Baillie-PSW probable prime test with parameters chosen by Selfridge’s method
as per [BaiWag1980].Return
if is a Lucas probable prime, otherwise return .There are no known composites passed as prime by this test, though infinitely many probably exist. The test will declare no primes composite.
-
int fmpz_is_probabprime(const fmpz_t p)¶
Performs some trial division and then some probabilistic primality tests. If
is definitely composite, the function returns , otherwise it is declared probably prime, i.e. prime for most practical purposes, and the function returns . The chance of declaring a composite prime is very small.Subsequent calls to the same function do not increase the probability of the number being prime.
-
int fmpz_is_prime_pseudosquare(const fmpz_t n)¶
Return
is is composite. If is too large (greater than about bits) the function fails silently and returns , otherwise, if is proven prime by the pseudosquares method, return .Tests if
is a prime according to Theorem 2.7 in [LukPatWil1996].We first factor
using trial division up to some limit . In fact, the number of primes used in the trial factoring is at mostFLINT_PSEUDOSQUARES_CUTOFF
.Next we compute
and find the next pseudosquare above this value, using a static table as per https://oeis.org/A002189/b002189.txt.As noted in the text, if
is prime then Step 3 will pass. This test rejects many composites, and so by this time we suspect that is prime. If is or modulo , we are done, and is prime.We now run a probable prime test, for which no known counterexamples are known, to reject any composites. We then proceed to prove
prime by executing Step 4. In the case that is modulo , if Step 4 fails, we extend the number of primes at Step 3 and hope to find one which passes Step 4. We take the test one past the largest for which we have pseudosquares tabulated, as this already corresponds to the next which is bigger than and hence larger than any prime we might be testing.As explained in the text, Condition 4 cannot fail if
is prime.The possibility exists that the probable prime test declares a composite prime. However in that case an error is printed, as that would be of independent interest.
-
int fmpz_is_prime_pocklington(fmpz_t F, fmpz_t R, const fmpz_t n, nn_ptr pm1, slong num_pm1)¶
Applies the Pocklington primality test. The test computes a product
of prime powers which divide .The function then returns either
if is definitely composite or it returns if all factors of are . Also in that case, is set to .NB: a return value of
only proves prime if .The function does not compute which primes divide
. Instead, these must be supplied as an arraypm1
of lengthnum_pm1
. It does not matter how many prime factors are supplied, but the more that are supplied, the larger F will be.There is a balance between the amount of time spent looking for factors of
and the usefulness of the output ( may be as low as in some cases).A reasonable heuristic seems to be to choose
limit
to be some small multiple of (e.g. or ) depending on how long one is prepared to wait, then to trial factor up to the limit. (See_fmpz_nm1_trial_factors
.)Requires
to be odd.
-
void _fmpz_nm1_trial_factors(const fmpz_t n, nn_ptr pm1, slong *num_pm1, ulong limit)¶
Trial factors
up to the given limit (approximately) and stores the factors in an arraypm1
whose length is written out tonum_pm1
.One can use
as a bound on the number of factors which might be produced (and hence on the length of the array that needs to be supplied).
-
int fmpz_is_prime_morrison(fmpz_t F, fmpz_t R, const fmpz_t n, nn_ptr pp1, slong num_pp1)¶
Applies the Morrison
primality test. The test computes a product of primes which divide .The function then returns either
if is definitely composite or it returns if all factors of are . Also in that case, is set to .NB: a return value of
only proves prime if .The function does not compute which primes divide
. Instead, these must be supplied as an arraypp1
of lengthnum_pp1
. It does not matter how many prime factors are supplied, but the more that are supplied, the larger will be.There is a balance between the amount of time spent looking for factors of
and the usefulness of the output ( may be as low as in some cases).A reasonable heuristic seems to be to choose
limit
to be some small multiple of (e.g. or ) depending on how long one is prepared to wait, then to trial factor up to the limit. (See_fmpz_np1_trial_factors
.)Requires
to be odd and non-square.
-
void _fmpz_np1_trial_factors(const fmpz_t n, nn_ptr pp1, slong *num_pp1, ulong limit)¶
Trial factors
up to the given limit (approximately) and stores the factors in an arraypp1
whose length is written out tonum_pp1
.One can use
as a bound on the number of factors which might be produced (and hence on the length of the array that needs to be supplied).
-
int fmpz_is_prime(const fmpz_t n)¶
Attempts to prove
prime. If is proven prime, the function returns . If is definitely composite, the function returns .This function calls
n_is_prime()
for that fits in a single word. For larger than one word, it tests divisibility by a few small primes and whether is a perfect square to rule out trivial composites. For up to about 81 bits, it then uses a strong probable prime test (Miller-Rabin test) with the first 13 primes as witnesses. This has been shown to prove primality [SorWeb2016].For larger
, it does a single base-2 strong probable prime test to eliminate most composite numbers. If passes, it does a combination of Pocklington, Morrison and Brillhart, Lehmer, Selfridge tests. If any of these tests fails to give a proof, it falls back to performing an APRCL test.The APRCL test could theoretically fail to prove that
is prime or composite. In that case, the program aborts. This is not expected to occur in practice.
-
void fmpz_lucas_chain(fmpz_t Vm, fmpz_t Vm1, const fmpz_t A, const fmpz_t m, const fmpz_t n)¶
Given
, compute from the recurrences .This is computed efficiently using
and .No aliasing is permitted.
-
void fmpz_lucas_chain_full(fmpz_t Vm, fmpz_t Vm1, const fmpz_t A, const fmpz_t B, const fmpz_t m, const fmpz_t n)¶
Given
, compute from the recurrences .This is computed efficiently using double and add formulas.
No aliasing is permitted.
-
void fmpz_lucas_chain_double(fmpz_t U2m, fmpz_t U2m1, const fmpz_t Um, const fmpz_t Um1, const fmpz_t A, const fmpz_t B, const fmpz_t n)¶
Given
compute .Aliasing of
and and aliasing of and is permitted. No other aliasing is allowed.
-
void fmpz_lucas_chain_add(fmpz_t Umn, fmpz_t Umn1, const fmpz_t Um, const fmpz_t Um1, const fmpz_t Un, const fmpz_t Un1, const fmpz_t A, const fmpz_t B, const fmpz_t n)¶
Given
and compute .Aliasing of
with or and aliasing of with or is permitted. No other aliasing is allowed.
-
void fmpz_lucas_chain_mul(fmpz_t Ukm, fmpz_t Ukm1, const fmpz_t Um, const fmpz_t Um1, const fmpz_t A, const fmpz_t B, const fmpz_t k, const fmpz_t n)¶
Given
compute .Aliasing of
and and aliasing of and is permitted. No other aliasing is allowed.
-
void fmpz_lucas_chain_VtoU(fmpz_t Um, fmpz_t Um1, const fmpz_t Vm, const fmpz_t Vm1, const fmpz_t A, const fmpz_t B, const fmpz_t Dinv, const fmpz_t n)¶
Given
compute .Aliasing of
and and aliasing of and is permitted. No other aliasing is allowed.
-
int fmpz_divisor_in_residue_class_lenstra(fmpz_t fac, const fmpz_t n, const fmpz_t r, const fmpz_t s)¶
If there exists a proper divisor of
which is for , this function returns and setsfac
to such a divisor. Otherwise the function returns and the value offac
is undefined.We require
.This is efficient if
.
-
void fmpz_nextprime(fmpz_t res, const fmpz_t n, int proved)¶
Finds the next prime number larger than
.If
proved
is nonzero, then the integer returned is guaranteed to actually be prime. Otherwise if fits inFLINT_BITS - 3
bitsn_nextprime
is called, and if not then the GMPmpz_nextprime
function is called which uses a BPSW test.
Special functions¶
-
void fmpz_primorial(fmpz_t res, ulong n)¶
Sets
res
ton
primorial or , the product of all prime numbers less than or equal to .
-
void fmpz_factor_euler_phi(fmpz_t res, const fmpz_factor_t fac)¶
-
void fmpz_euler_phi(fmpz_t res, const fmpz_t n)¶
Sets
res
to the Euler totient function , counting the number of positive integers less than or equal to that are coprime to . The factor version takes a precomputed factorisation of .
-
int fmpz_factor_moebius_mu(const fmpz_factor_t fac)¶
-
int fmpz_moebius_mu(const fmpz_t n)¶
Computes the Moebius function
, which is defined as if has a prime factor of multiplicity greater than , if has an odd number of distinct prime factors, and if has an even number of distinct prime factors. By convention, . The factor version takes a precomputed factorisation of .