Next: Rational Number Functions, Previous: Reporting Bugs, Up: GNU MP [Index]
This chapter describes the GMP functions for performing integer arithmetic.
These functions start with the prefix mpz_
.
GMP integers are stored in objects of type mpz_t
.
Next: Assignment Functions, Previous: Integer Functions, Up: Integer Functions [Index]
The functions for integer arithmetic assume that all integer objects are
initialized. You do that by calling the function mpz_init
. For
example,
{ mpz_t integ; mpz_init (integ); … mpz_add (integ, …); … mpz_sub (integ, …); /* Unless the program is about to exit, do ... */ mpz_clear (integ); }
As you can see, you can store new values any number of times, once an object is initialized.
Initialize x, and set its value to 0.
Initialize a NULL-terminated list of mpz_t
variables, and set their
values to 0.
Initialize x, with space for n-bit numbers, and set its value to 0.
Calling this function instead of mpz_init
or mpz_inits
is never
necessary; reallocation is handled automatically by GMP when needed.
While n defines the initial space, x will grow automatically in the
normal way, if necessary, for subsequent values stored. mpz_init2
makes
it possible to avoid such reallocations if a maximum size is known in advance.
In preparation for an operation, GMP often allocates one limb more than
ultimately needed. To make sure GMP will not perform reallocation for
x, you need to add the number of bits in mp_limb_t
to n.
Free the space occupied by x. Call this function for all mpz_t
variables when you are done with them.
Free the space occupied by a NULL-terminated list of mpz_t
variables.
Change the space allocated for x to n bits. The value in x is preserved if it fits, or is set to 0 if not.
Calling this function is never necessary; reallocation is handled automatically by GMP when needed. But this function can be used to increase the space for a variable in order to avoid repeated automatic reallocations, or to decrease it to give memory back to the heap.
Next: Combined Initialization and Assignment Functions, Previous: Initialization Functions, Up: Integer Functions [Index]
These functions assign new values to already initialized integers (see Initialization Functions).
Set the value of rop from op.
mpz_set_d
, mpz_set_q
and mpz_set_f
truncate op to
make it an integer.
Set the value of rop from str, a null-terminated C string in base base. White space is allowed in the string, and is simply ignored.
The base may vary from 2 to 62, or if base is 0, then the leading
characters are used: 0x
and 0X
for hexadecimal, 0b
and
0B
for binary, 0
for octal, or decimal otherwise.
For bases up to 36, case is ignored; upper-case and lower-case letters have the same value. For bases 37 to 62, upper-case letter represent the usual 10..35 while lower-case letter represent 36..61.
This function returns 0 if the entire string is a valid number in base base. Otherwise it returns -1.
Swap the values rop1 and rop2 efficiently.
Next: Conversion Functions, Previous: Assignment Functions, Up: Integer Functions [Index]
For convenience, GMP provides a parallel series of initialize-and-set functions
which initialize the output and then store the value there. These functions’
names have the form mpz_init_set…
Here is an example of using one:
{ mpz_t pie; mpz_init_set_str (pie, "3141592653589793238462643383279502884", 10); … mpz_sub (pie, …); … mpz_clear (pie); }
Once the integer has been initialized by any of the mpz_init_set…
functions, it can be used as the source or destination operand for the ordinary
integer functions. Don’t use an initialize-and-set function on a variable
already initialized!
Initialize rop with limb space and set the initial numeric value from op.
Initialize rop and set its value like mpz_set_str
(see its
documentation above for details).
If the string is a correct base base number, the function returns 0;
if an error occurs it returns -1. rop is initialized even if
an error occurs. (I.e., you have to call mpz_clear
for it.)
Next: Arithmetic Functions, Previous: Combined Initialization and Assignment Functions, Up: Integer Functions [Index]
This section describes functions for converting GMP integers to standard C types. Functions for converting to GMP integers are described in Assignment Functions and Input and Output Functions.
Return the value of op as an unsigned long
.
If op is too big to fit an unsigned long
then just the least
significant bits that do fit are returned. The sign of op is ignored,
only the absolute value is used.
If op fits into a signed long int
return the value of op.
Otherwise return the least significant part of op, with the same sign
as op.
If op is too big to fit in a signed long int
, the returned
result is probably not very useful. To find out if the value will fit, use
the function mpz_fits_slong_p
.
Convert op to a double
, truncating if necessary (i.e. rounding
towards zero).
If the exponent from the conversion is too big, the result is system dependent. An infinity is returned where available. A hardware overflow trap may or may not occur.
Convert op to a double
, truncating if necessary (i.e. rounding
towards zero), and returning the exponent separately.
The return value is in the range 0.5<=abs(d)<1 and the
exponent is stored to *exp
. d *
2^exp is the (truncated) op value. If op is zero, the
return is 0.0 and 0 is stored to *exp
.
This is similar to the standard C frexp
function (see Normalization
Functions in The GNU C Library Reference Manual).
Convert op to a string of digits in base base. The base argument may vary from 2 to 62 or from -2 to -36.
For base in the range 2..36, digits and lower-case letters are used; for -2..-36, digits and upper-case letters are used; for 37..62, digits, upper-case letters, and lower-case letters (in that significance order) are used.
If str is NULL
, the result string is allocated using the current
allocation function (see Custom Allocation). The block will be
strlen(str)+1
bytes, that being exactly enough for the string and
null-terminator.
If str is not NULL
, it should point to a block of storage large
enough for the result, that being mpz_sizeinbase (op, base)
+ 2
. The two extra bytes are for a possible minus sign, and the
null-terminator.
A pointer to the result string is returned, being either the allocated block, or the given str.
Next: Division Functions, Previous: Conversion Functions, Up: Integer Functions [Index]
Set rop to op1 + op2.
Set rop to op1 - op2.
Set rop to op1 times op2.
Set rop to rop + op1 times op2.
Set rop to rop - op1 times op2.
Set rop to op1 times 2 raised to op2. This operation can also be defined as a left shift by op2 bits.
Set rop to -op.
Set rop to the absolute value of op.
Next: Exponentiation Functions, Previous: Arithmetic Functions, Up: Integer Functions [Index]
Division is undefined if the divisor is zero. Passing a zero divisor to the
division or modulo functions (including the modular powering functions
mpz_powm
and mpz_powm_ui
), will cause an intentional division by
zero. This lets a program handle arithmetic exceptions in these functions the
same way as for normal C int
arithmetic.
Divide n by d, forming a quotient q and/or remainder
r. For the 2exp
functions, d=2^b.
The rounding is in three styles, each suiting different applications.
cdiv
rounds q up towards +infinity, and r will
have the opposite sign to d. The c
stands for “ceil”.
fdiv
rounds q down towards -infinity, and
r will have the same sign as d. The f
stands for
“floor”.
tdiv
rounds q towards zero, and r will have the same sign
as n. The t
stands for “truncate”.
In all cases q and r will satisfy n=q*d+r, and r will satisfy 0<=abs(r)<abs(d).
The q
functions calculate only the quotient, the r
functions
only the remainder, and the qr
functions calculate both. Note that for
qr
the same variable cannot be passed for both q and r, or
results will be unpredictable.
For the ui
variants the return value is the remainder, and in fact
returning the remainder is all the div_ui
functions do. For
tdiv
and cdiv
the remainder can be negative, so for those the
return value is the absolute value of the remainder.
For the 2exp
variants the divisor is 2^b. These
functions are implemented as right shifts and bit masks, but of course they
round the same as the other functions.
For positive n both mpz_fdiv_q_2exp
and mpz_tdiv_q_2exp
are simple bitwise right shifts. For negative n, mpz_fdiv_q_2exp
is effectively an arithmetic right shift treating n as twos complement
the same as the bitwise logical functions do, whereas mpz_tdiv_q_2exp
effectively treats n as sign and magnitude.
Set r to n mod
d. The sign of the divisor is
ignored; the result is always non-negative.
mpz_mod_ui
is identical to mpz_fdiv_r_ui
above, returning the
remainder as well as setting r. See mpz_fdiv_ui
above if only
the return value is wanted.
Set q to n/d. These functions produce correct results only when it is known in advance that d divides n.
These routines are much faster than the other division functions, and are the best choice when exact division is known to occur, for example reducing a rational to lowest terms.
Return non-zero if n is exactly divisible by d, or in the case of
mpz_divisible_2exp_p
by 2^b.
n is divisible by d if there exists an integer q satisfying n = q*d. Unlike the other division functions, d=0 is accepted and following the rule it can be seen that only 0 is considered divisible by 0.
Return non-zero if n is congruent to c modulo d, or in the
case of mpz_congruent_2exp_p
modulo 2^b.
n is congruent to c mod d if there exists an integer q satisfying n = c + q*d. Unlike the other division functions, d=0 is accepted and following the rule it can be seen that n and c are considered congruent mod 0 only when exactly equal.
Next: Root Extraction Functions, Previous: Division Functions, Up: Integer Functions [Index]
Set rop to (base raised to exp) modulo mod.
Negative exp is supported if the inverse base-1 mod
mod exists (see mpz_invert
in
Number Theoretic Functions). If an inverse doesn’t exist then a divide
by zero is raised.
Set rop to (base raised to exp) modulo mod.
It is required that exp > 0 and that mod is odd.
This function is designed to take the same time and have the same cache access patterns for any two same-size arguments, assuming that function arguments are placed at the same position and that the machine state is identical upon function entry. This function is intended for cryptographic purposes, where resilience to side-channel attacks is desired.
Set rop to base raised to exp. The case 0^0 yields 1.
Next: Number Theoretic Functions, Previous: Exponentiation Functions, Up: Integer Functions [Index]
Set rop to the truncated integer part of the nth root of op. Return non-zero if the computation was exact, i.e., if op is rop to the nth power.
Set root to the truncated integer part of the nth root of u. Set rem to the remainder, u-root**n.
Set rop to the truncated integer part of the square root of op.
Set rop1 to the truncated integer part
of the square root of op, like mpz_sqrt
. Set rop2 to the
remainder op-rop1*rop1, which will be zero if op is a
perfect square.
If rop1 and rop2 are the same variable, the results are undefined.
Return non-zero if op is a perfect power, i.e., if there exist integers a and b, with b>1, such that op equals a raised to the power b.
Under this definition both 0 and 1 are considered to be perfect powers. Negative values of op are accepted, but of course can only be odd perfect powers.
Return non-zero if op is a perfect square, i.e., if the square root of op is an integer. Under this definition both 0 and 1 are considered to be perfect squares.
Next: Comparison Functions, Previous: Root Extraction Functions, Up: Integer Functions [Index]
Determine whether n is prime. Return 2 if n is definitely prime, return 1 if n is probably prime (without being certain), or return 0 if n is definitely non-prime.
This function performs some trial divisions, a Baillie-PSW probable prime test, then reps-24 Miller-Rabin probabilistic primality tests. A higher reps value will reduce the chances of a non-prime being identified as “probably prime”. A composite number will be identified as a prime with an asymptotic probability of less than 4^(-reps). Reasonable values of reps are between 15 and 50.
GMP versions up to and including 6.1.2 did not use the Baillie-PSW primality test. In those older versions of GMP, this function performed reps Miller-Rabin tests.
Set rop to the next prime greater than op.
This function uses a probabilistic algorithm to identify primes. For practical purposes it’s adequate, the chance of a composite passing will be extremely small.
Set rop to the greatest common divisor of op1 and op2. The result is always positive even if one or both input operands are negative. Except if both inputs are zero; then this function defines gcd(0,0) = 0.
Compute the greatest common divisor of op1 and op2. If
rop is not NULL
, store the result there.
If the result is small enough to fit in an unsigned long int
, it is
returned. If the result does not fit, 0 is returned, and the result is equal
to the argument op1. Note that the result will always fit if op2
is non-zero.
Set g to the greatest common divisor of a and b, and in addition set s and t to coefficients satisfying a*s + b*t = g. The value in g is always positive, even if one or both of a and b are negative (or zero if both inputs are zero). The values in s and t are chosen such that normally, abs(s) < abs(b) / (2 g) and abs(t) < abs(a) / (2 g), and these relations define s and t uniquely. There are a few exceptional cases:
If abs(a) = abs(b), then s = 0, t = sgn(b).
Otherwise, s = sgn(a) if b = 0 or abs(b) = 2 g, and t = sgn(b) if a = 0 or abs(a) = 2 g.
In all cases, s = 0 if and only if g = abs(b), i.e., if b divides a or a = b = 0.
If t or g is NULL
then that value is not computed.
Set rop to the least common multiple of op1 and op2. rop is always positive, irrespective of the signs of op1 and op2. rop will be zero if either op1 or op2 is zero.
Compute the inverse of op1 modulo op2 and put the result in rop. If the inverse exists, the return value is non-zero and rop will satisfy 0 <= rop < abs(op2) (with rop = 0 possible only when abs(op2) = 1, i.e., in the somewhat degenerate zero ring). If an inverse doesn’t exist the return value is zero and rop is undefined. The behaviour of this function is undefined when op2 is zero.
Calculate the Jacobi symbol (a/b). This is defined only for b odd.
Calculate the Legendre symbol (a/p). This is defined only for p an odd positive prime, and for such p it’s identical to the Jacobi symbol.
Calculate the Jacobi symbol (a/b) with the Kronecker extension (a/2)=(2/a) when a odd, or (a/2)=0 when a even.
When b is odd the Jacobi symbol and Kronecker symbol are
identical, so mpz_kronecker_ui
etc can be used for mixed
precision Jacobi symbols too.
For more information see Henri Cohen section 1.4.2 (see References),
or any number theory textbook. See also the example program
demos/qcn.c which uses mpz_kronecker_ui
.
Remove all occurrences of the factor f from op and store the result in rop. The return value is how many such occurrences were removed.
Set rop to the factorial of n: mpz_fac_ui
computes the plain factorial n!,
mpz_2fac_ui
computes the double-factorial n!!, and mpz_mfac_uiui
the
m-multi-factorial n!^(m).
Set rop to the primorial of n, i.e. the product of all positive prime numbers <=n.
Compute the binomial coefficient n over
k and store the result in rop. Negative values of n are
supported by mpz_bin_ui
, using the identity
bin(-n,k) = (-1)^k * bin(n+k-1,k), see Knuth volume 1 section 1.2.6
part G.
mpz_fib_ui
sets fn to to F[n], the n’th Fibonacci
number. mpz_fib2_ui
sets fn to F[n], and fnsub1 to
F[n-1].
These functions are designed for calculating isolated Fibonacci numbers. When
a sequence of values is wanted it’s best to start with mpz_fib2_ui
and
iterate the defining F[n+1]=F[n]+F[n-1] or
similar.
mpz_lucnum_ui
sets ln to to L[n], the n’th Lucas
number. mpz_lucnum2_ui
sets ln to L[n], and lnsub1
to L[n-1].
These functions are designed for calculating isolated Lucas numbers. When a
sequence of values is wanted it’s best to start with mpz_lucnum2_ui
and
iterate the defining L[n+1]=L[n]+L[n-1] or
similar.
The Fibonacci numbers and Lucas numbers are related sequences, so it’s never
necessary to call both mpz_fib2_ui
and mpz_lucnum2_ui
. The
formulas for going from Fibonacci to Lucas can be found in Lucas Numbers, the reverse is straightforward too.
Next: Logical and Bit Manipulation Functions, Previous: Number Theoretic Functions, Up: Integer Functions [Index]
Compare op1 and op2. Return a positive value if op1 > op2, zero if op1 = op2, or a negative value if op1 < op2.
mpz_cmp_ui
and mpz_cmp_si
are macros and will evaluate their
arguments more than once. mpz_cmp_d
can be called with an infinity,
but results are undefined for a NaN.
Compare the absolute values of op1 and op2. Return a positive value if abs(op1) > abs(op2), zero if abs(op1) = abs(op2), or a negative value if abs(op1) < abs(op2).
mpz_cmpabs_d
can be called with an infinity, but results are undefined
for a NaN.
Return +1 if op > 0, 0 if op = 0, and -1 if op < 0.
This function is actually implemented as a macro. It evaluates its argument multiple times.
Next: Input and Output Functions, Previous: Comparison Functions, Up: Integer Functions [Index]
These functions behave as if twos complement arithmetic were used (although sign-magnitude is the actual implementation). The least significant bit is number 0.
Set rop to op1 bitwise-and op2.
Set rop to op1 bitwise inclusive-or op2.
Set rop to op1 bitwise exclusive-or op2.
Set rop to the one’s complement of op.
If op>=0, return the population count of op, which is the
number of 1 bits in the binary representation. If op<0, the
number of 1s is infinite, and the return value is the largest possible
mp_bitcnt_t
.
If op1 and op2 are both >=0 or both <0, return the
hamming distance between the two operands, which is the number of bit positions
where op1 and op2 have different bit values. If one operand is
>=0 and the other <0 then the number of bits different is
infinite, and the return value is the largest possible mp_bitcnt_t
.
Scan op, starting from bit starting_bit, towards more significant bits, until the first 0 or 1 bit (respectively) is found. Return the index of the found bit.
If the bit at starting_bit is already what’s sought, then starting_bit is returned.
If there’s no bit found, then the largest possible mp_bitcnt_t
is
returned. This will happen in mpz_scan0
past the end of a negative
number, or mpz_scan1
past the end of a nonnegative number.
Set bit bit_index in rop.
Clear bit bit_index in rop.
Complement bit bit_index in rop.
Test bit bit_index in op and return 0 or 1 accordingly.
Next: Random Number Functions, Previous: Logical and Bit Manipulation Functions, Up: Integer Functions [Index]
Functions that perform input from a stdio stream, and functions that output to
a stdio stream, of mpz
numbers. Passing a NULL
pointer for a
stream argument to any of these functions will make them read from
stdin
and write to stdout
, respectively.
When using any of these functions, it is a good idea to include stdio.h before gmp.h, since that will allow gmp.h to define prototypes for these functions.
See also Formatted Output and Formatted Input.
Output op on stdio stream stream, as a string of digits in base base. The base argument may vary from 2 to 62 or from -2 to -36.
For base in the range 2..36, digits and lower-case letters are used; for -2..-36, digits and upper-case letters are used; for 37..62, digits, upper-case letters, and lower-case letters (in that significance order) are used.
Return the number of bytes written, or if an error occurred, return 0.
Input a possibly white-space preceded string in base base from stdio stream stream, and put the read integer in rop.
The base may vary from 2 to 62, or if base is 0, then the leading
characters are used: 0x
and 0X
for hexadecimal, 0b
and
0B
for binary, 0
for octal, or decimal otherwise.
For bases up to 36, case is ignored; upper-case and lower-case letters have the same value. For bases 37 to 62, upper-case letter represent the usual 10..35 while lower-case letter represent 36..61.
Return the number of bytes read, or if an error occurred, return 0.
Output op on stdio stream stream, in raw binary format. The integer is written in a 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 mpz_inp_raw
.
Return the number of bytes written, or if an error occurred, return 0.
The output of this can not be read by mpz_inp_raw
from GMP 1, because
of changes necessary for compatibility between 32-bit and 64-bit machines.
Input from stdio stream stream in the format written by
mpz_out_raw
, and put the result in rop. Return the number of
bytes read, or if an error occurred, return 0.
This routine can read the output from mpz_out_raw
also from GMP 1, in
spite of changes necessary for compatibility between 32-bit and 64-bit
machines.
Next: Integer Import and Export, Previous: Input and Output Functions, Up: Integer Functions [Index]
The random number functions of GMP come in two groups; older function that rely on a global state, and newer functions that accept a state parameter that is read and modified. Please see the Random Number Functions for more information on how to use and not to use random number functions.
Generate a uniformly distributed random integer in the range 0 to 2n-1, inclusive.
The variable state must be initialized by calling one of the
gmp_randinit
functions (Random State Initialization) before
invoking this function.
Generate a uniform random integer in the range 0 to n-1, inclusive.
The variable state must be initialized by calling one of the
gmp_randinit
functions (Random State Initialization)
before invoking this function.
Generate a random integer with long strings of zeros and ones in the binary representation. Useful for testing functions and algorithms, since this kind of random numbers have proven to be more likely to trigger corner-case bugs. The random number will be in the range 2n-1 to 2n-1, inclusive.
The variable state must be initialized by calling one of the
gmp_randinit
functions (Random State Initialization)
before invoking this function.
Generate a random integer of at most max_size limbs. The generated random number doesn’t satisfy any particular requirements of randomness. Negative random numbers are generated when max_size is negative.
This function is obsolete. Use mpz_urandomb
or
mpz_urandomm
instead.
Generate a random integer of at most max_size limbs, with long strings of zeros and ones in the binary representation. Useful for testing functions and algorithms, since this kind of random numbers have proven to be more likely to trigger corner-case bugs. Negative random numbers are generated when max_size is negative.
This function is obsolete. Use mpz_rrandomb
instead.
Next: Miscellaneous Functions, Previous: Random Number Functions, Up: Integer Functions [Index]
mpz_t
variables can be converted to and from arbitrary words of binary
data with the following functions.
Set rop from an array of word data at op.
The parameters specify the format of the data. count many words are read, each size bytes. order can be 1 for most significant word first or -1 for least significant first. Within each word endian can be 1 for most significant byte first, -1 for least significant first, or 0 for the native endianness of the host CPU. The most significant nails bits of each word are skipped, this can be 0 to use the full words.
There is no sign taken from the data, rop will simply be a positive
integer. An application can handle any sign itself, and apply it for instance
with mpz_neg
.
There are no data alignment restrictions on op, any address is allowed.
Here’s an example converting an array of unsigned long
data, most
significant element first, and host byte order within each value.
unsigned long a[20]; /* Initialize z and a */ mpz_import (z, 20, 1, sizeof(a[0]), 0, 0, a);
This example assumes the full sizeof
bytes are used for data in the
given type, which is usually true, and certainly true for unsigned long
everywhere we know of. However on Cray vector systems it may be noted that
short
and int
are always stored in 8 bytes (and with
sizeof
indicating that) but use only 32 or 46 bits. The nails
feature can account for this, by passing for instance
8*sizeof(int)-INT_BIT
.
Fill rop with word data from op.
The parameters specify the format of the data produced. Each word will be size bytes and order can be 1 for most significant word first or -1 for least significant first. Within each word endian can be 1 for most significant byte first, -1 for least significant first, or 0 for the native endianness of the host CPU. The most significant nails bits of each word are unused and set to zero, this can be 0 to produce full words.
The number of words produced is written to *countp
, or
countp can be NULL
to discard the count. rop must have
enough space for the data, or if rop is NULL
then a result array
of the necessary size is allocated using the current GMP allocation function
(see Custom Allocation). In either case the return value is the
destination used, either rop or the allocated block.
If op is non-zero then the most significant word produced will be
non-zero. If op is zero then the count returned will be zero and
nothing written to rop. If rop is NULL
in this case, no
block is allocated, just NULL
is returned.
The sign of op is ignored, just the absolute value is exported. An
application can use mpz_sgn
to get the sign and handle it as desired.
(see Comparison Functions)
There are no data alignment restrictions on rop, any address is allowed.
When an application is allocating space itself the required size can be
determined with a calculation like the following. Since mpz_sizeinbase
always returns at least 1, count
here will be at least one, which
avoids any portability problems with malloc(0)
, though if z
is
zero no space at all is actually needed (or written).
numb = 8*size - nail; count = (mpz_sizeinbase (z, 2) + numb-1) / numb; p = malloc (count * size);
Next: Special Functions, Previous: Integer Import and Export, Up: Integer Functions [Index]
Return non-zero iff the value of op fits in an unsigned long int
,
signed long int
, unsigned int
, signed int
, unsigned
short int
, or signed short int
, respectively. Otherwise, return zero.
Determine whether op is odd or even, respectively. Return non-zero if yes, zero if no. These macros evaluate their argument more than once.
Return the size of op measured in number of digits in the given base. base can vary from 2 to 62. The sign of op is ignored, just the absolute value is used. The result will be either exact or 1 too big. If base is a power of 2, the result is always exact. If op is zero the return value is always 1.
This function can be used to determine the space required when converting
op to a string. The right amount of allocation is normally two more
than the value returned by mpz_sizeinbase
, one extra for a minus sign
and one for the null-terminator.
It will be noted that mpz_sizeinbase(op,2)
can be used to locate
the most significant 1 bit in op, counting from 1. (Unlike the bitwise
functions which start from 0, See Logical
and Bit Manipulation Functions.)
Previous: Miscellaneous Functions, Up: Integer Functions [Index]
The functions in this section are for various special purposes. Most applications will not need them.
This is an obsolete function. Do not use it.
Change the space for integer to new_alloc limbs. The value in integer is preserved if it fits, or is set to 0 if not. The return value is not useful to applications and should be ignored.
mpz_realloc2
is the preferred way to accomplish allocation changes like
this. mpz_realloc2
and _mpz_realloc
are the same except that
_mpz_realloc
takes its size in limbs.
Return limb number n from op. The sign of op is ignored, just the absolute value is used. The least significant limb is number 0.
mpz_size
can be used to find how many limbs make up op.
mpz_getlimbn
returns zero if n is outside the range 0 to
mpz_size(op)-1
.
Return the size of op measured in number of limbs. If op is zero, the returned value will be zero.
Return a pointer to the limb array representing the absolute value of x.
The size of the array is mpz_size(x)
. Intended for read access
only.
Return a pointer to the limb array, intended for write access. The array is
reallocated as needed, to make room for n limbs. Requires n
> 0. The mpz_limbs_modify
function returns an array that holds the old
absolute value of x, while mpz_limbs_write
may destroy the old
value and return an array with unspecified contents.
Updates the internal size field of x. Used after writing to the limb
array pointer returned by mpz_limbs_write
or mpz_limbs_modify
is
completed. The array should contain abs(s) valid limbs,
representing the new absolute value for x, and the sign of x is
taken from the sign of s. This function never reallocates x, so
the limb pointer remains valid.
void foo (mpz_t x) { mp_size_t n, i; mp_limb_t *xp; n = mpz_size (x); xp = mpz_limbs_modify (x, 2*n); for (i = 0; i < n; i++) xp[n+i] = xp[n-1-i]; mpz_limbs_finish (x, mpz_sgn (x) < 0 ? - 2*n : 2*n); }
Special initialization of x, using the given limb array and size. x should be treated as read-only: it can be passed safely as input to any mpz function, but not as an output. The array xp must point to at least a readable limb, its size is abs(xs), and the sign of x is the sign of xs. For convenience, the function returns x, but cast to a const pointer type.
void foo (mpz_t x) { static const mp_limb_t y[3] = { 0x1, 0x2, 0x3 }; mpz_t tmp; mpz_add (x, x, mpz_roinit_n (tmp, y, 3)); }
This macro expands to an initializer which can be assigned to an mpz_t
variable. The limb array xp must point to at least a readable limb,
moreover, unlike the mpz_roinit_n
function, the array must be
normalized: if xs is non-zero, then
xp[abs(xs)-1]
must be non-zero. Intended
primarily for constant values. Using it for non-constant values requires a C
compiler supporting C99.
void foo (mpz_t x) { static const mp_limb_t ya[3] = { 0x1, 0x2, 0x3 }; static const mpz_t y = MPZ_ROINIT_N ((mp_limb_t *) ya, 3); mpz_add (x, x, y); }
Next: Rational Number Functions, Previous: Reporting Bugs, Up: GNU MP [Index]