This is gmp.info, produced by makeinfo version 4.0 from gmp.texi.

INFO-DIR-SECTION GNU libraries
START-INFO-DIR-ENTRY
* gmp: (gmp).                   GNU Multiple Precision Arithmetic Library.
END-INFO-DIR-ENTRY


File: gmp.info,  Node: Efficiency,  Next: Debugging,  Prev: Compatibility with older versions,  Up: GMP Basics

Efficiency
==========

Small operands
     On small operands, the time for function call overheads and memory
     allocation can be significant in comparison to actual calculation.
     This is unavoidable in a general purpose variable precision
     library, although GMP attempts to be as efficient as it can on
     both large and small operands.

Static Linking
     On some CPUs, in particular the x86s, the static `libgmp.a' should
     be used for maximum speed, since the PIC code in the shared
     `libgmp.so' will have a small overhead on each function call and
     global data address.  For many programs this will be
     insignificant, but for long calculations there's a gain to be had.

Initializing and clearing
     Avoid excessive initializing and clearing of variables, since this
     can be quite time consuming, especially in comparison to otherwise
     fast operations like addition.

     A language interpreter might want to keep a free list or stack of
     initialized variables ready for use.  It should be possible to
     integrate something like that with a garbage collector too.

Reallocations
     An `mpz_t' or `mpq_t' variable used to hold successively increasing
     values will have its memory repeatedly `realloc'ed, which could be
     quite slow or could fragment memory, depending on the C library.
     If an application can estimate the final size then `mpz_init2' or
     `mpz_realloc2' can be called to allocate the necessary space from
     the beginning (*note Initializing Integers::).

     It doesn't matter if a size set with `mpz_init2' or `mpz_realloc2'
     is too small, since all functions will do a further reallocation
     if necessary.  Badly overestimating memory required will waste
     space though.

`2exp' functions
     It's up to an application to call functions like `mpz_mul_2exp'
     when appropriate.  General purpose functions like `mpz_mul' make
     no attempt to identify powers of two or other special forms,
     because such inputs will usually be very rare and testing every
     time would be wasteful.

`ui' and `si' functions
     The `ui' functions and the small number of `si' functions exist for
     convenience and should be used where applicable.  But if for
     example an `mpz_t' contains a value that fits in an `unsigned
     long' there's no need extract it and call a `ui' function, just
     use the regular `mpz' function.

In-Place Operations
     `mpz_abs', `mpq_abs', `mpf_abs', `mpz_neg', `mpq_neg' and
     `mpf_neg' are fast when used for in-place operations like
     `mpz_abs(x,x)', since in the current implementation only a single
     field of `x' needs changing.  On suitable compilers (GCC for
     instance) this is inlined too.

     `mpz_add_ui', `mpz_sub_ui', `mpf_add_ui' and `mpf_sub_ui' benefit
     from an in-place operation like `mpz_add_ui(x,x,y)', since usually
     only one or two limbs of `x' will need to be changed.  The same
     applies to the full precision `mpz_add' etc if `y' is small.  If
     `y' is big then cache locality may be helped, but that's all.

     `mpz_mul' is currently the opposite, a separate destination is
     slightly better.  A call like `mpz_mul(x,x,y)' will, unless `y' is
     only one limb, make a temporary copy of `x' before forming the
     result.  Normally that copying will only be a tiny fraction of the
     time for the multiply, so this is not a particularly important
     consideration.

     `mpz_set', `mpq_set', `mpq_set_num', `mpf_set', etc, make no
     attempt to recognise a copy of something to itself, so a call like
     `mpz_set(x,x)' will be wasteful.  Naturally that would never be
     written deliberately, but if it might arise from two pointers to
     the same object then a test to avoid it might be desirable.

          if (x != y)
            mpz_set (x, y);

     Note that it's never worth introducing extra `mpz_set' calls just
     to get in-place operations.  If a result should go to a particular
     variable then just direct it there and let GMP take care of data
     movement.

Divisibility Testing (Small Integers)
     `mpz_divisible_ui_p' and `mpz_congruent_ui_p' are the best
     functions for testing whether an `mpz_t' is divisible by an
     individual small integer.  They use an algorithm which is faster
     than `mpz_tdiv_ui', but which gives no useful information about
     the actual remainder, only whether it's zero (or a particular
     value).

     However when testing divisibility by several small integers, it's
     best to take a remainder modulo their product, to save
     multi-precision operations.  For instance to test whether a number
     is divisible by any of 23, 29 or 31 take a remainder modulo
     23*29*31 = 20677 and then test that.

     The division functions like `mpz_tdiv_q_ui' which give a quotient
     as well as a remainder are generally a little slower than the
     remainder-only functions like `mpz_tdiv_ui'.  If the quotient is
     only rarely wanted then it's probably best to just take a
     remainder and then go back and calculate the quotient if and when
     it's wanted (`mpz_divexact_ui' can be used if the remainder is
     zero).

Rational Arithmetic
     The `mpq' functions operate on `mpq_t' values with no common
     factors in the numerator and denominator.  Common factors are
     checked-for and cast out as necessary.  In general, cancelling
     factors every time is the best approach since it minimizes the
     sizes for subsequent operations.

     However, applications that know something about the factorization
     of the values they're working with might be able to avoid some of
     the GCDs used for canonicalization, or swap them for divisions.
     For example when multiplying by a prime it's enough to check for
     factors of it in the denominator instead of doing a full GCD.  Or
     when forming a big product it might be known that very little
     cancellation will be possible, and so canonicalization can be left
     to the end.

     The `mpq_numref' and `mpq_denref' macros give access to the
     numerator and denominator to do things outside the scope of the
     supplied `mpq' functions.  *Note Applying Integer Functions::.

     The canonical form for rationals allows mixed-type `mpq_t' and
     integer additions or subtractions to be done directly with
     multiples of the denominator.  This will be somewhat faster than
     `mpq_add'.  For example,

          /* mpq increment */
          mpz_add (mpq_numref(q), mpq_numref(q), mpq_denref(q));
          
          /* mpq += unsigned long */
          mpz_addmul_ui (mpq_numref(q), mpq_denref(q), 123UL);
          
          /* mpq -= mpz */
          mpz_submul (mpq_numref(q), mpq_denref(q), z);

Number Sequences
     Functions like `mpz_fac_ui', `mpz_fib_ui' and `mpz_bin_uiui' are
     designed for calculating isolated values.  If a range of values is
     wanted it's probably best to call to get a starting point and
     iterate from there.


File: gmp.info,  Node: Debugging,  Next: Profiling,  Prev: Efficiency,  Up: GMP Basics

Debugging
=========

Stack Overflow
     Depending on the system, a segmentation violation or bus error
     might be the only indication of stack overflow.  See
     `--enable-alloca' choices in *Note Build Options::, for how to
     address this.

Heap Problems
     The most likely cause of application problems with GMP is heap
     corruption.  Failing to `init' GMP variables will have
     unpredictable effects, and corruption arising elsewhere in a
     program may well affect GMP.  Initializing GMP variables more than
     once or failing to clear them will cause memory leaks.

     In all such cases a malloc debugger is recommended.  On a GNU or
     BSD system the standard C library `malloc' has some diagnostic
     facilities, see *Note Allocation Debugging: (libc)Allocation
     Debugging, or `man 3 malloc'.  Other possibilities, in no
     particular order, include

          `http://www.inf.ethz.ch/personal/biere/projects/ccmalloc'
          `http://quorum.tamu.edu/jon/gnu'  (debauch)
          `http://dmalloc.com'
          `http://www.perens.com/FreeSoftware'  (electric fence)
          `http://packages.debian.org/fda'
          `http://www.gnupdate.org/components/leakbug'
          `http://people.redhat.com/~otaylor/memprof'
          `http://www.cbmamiga.demon.co.uk/mpatrol'

Stack Backtraces
     On some systems the compiler options GMP uses by default can
     interfere with debugging.  In particular on x86 and 68k systems
     `-fomit-frame-pointer' is used and this generally inhibits stack
     backtracing.  Recompiling without such options may help while
     debugging, though the usual caveats about it potentially moving a
     memory problem or hiding a compiler bug will apply.

GNU Debugger
     A sample `.gdbinit' is included in the distribution, showing how
     to call some undocumented dump functions to print GMP variables
     from within GDB.  Note that these functions shouldn't be used in
     final application code since they're undocumented and may be
     subject to incompatible changes in future versions of GMP.

Source File Paths
     GMP has multiple source files with the same name, in different
     directories.  For example `mpz', `mpq', `mpf' and `mpfr' each have
     an `init.c'.  If the debugger can't already determine the right
     one it may help to build with absolute paths on each C file.  One
     way to do that is to use a separate object directory with an
     absolute path to the source directory.

          cd /my/build/dir
          /my/source/dir/gmp-4.0.1/configure

     This works via `VPATH', and might require GNU `make'.  Alternately
     it might be possible to change the `.c.lo' rules appropriately.

Assertion Checking
     The build option `--enable-assert' is available to add some
     consistency checks to the library (see *Note Build Options::).
     These are likely to be of limited value to most applications.
     Assertion failures are just as likely to indicate memory
     corruption as a library or compiler bug.

     Applications using the low-level `mpn' functions, however, will
     benefit from `--enable-assert' since it adds checks on the
     parameters of most such functions, many of which have subtle
     restrictions on their usage.  Note however that only the generic C
     code has checks, not the assembler code, so CPU `none' should be
     used for maximum checking.

Temporary Memory Checking
     The build option `--enable-alloca=debug' arranges that each block
     of temporary memory in GMP is allocated with a separate call to
     `malloc' (or the allocation function set with
     `mp_set_memory_functions').

     This can help a malloc debugger detect accesses outside the
     intended bounds, or detect memory not released.  In a normal
     build, on the other hand, temporary memory is allocated in blocks
     which GMP divides up for its own use, or may be allocated with a
     compiler builtin `alloca' which will go nowhere near any malloc
     debugger hooks.

Other Problems
     Any suspected bug in GMP itself should be isolated to make sure
     it's not an application problem, see *Note Reporting Bugs::.


File: gmp.info,  Node: Profiling,  Next: Autoconf,  Prev: Debugging,  Up: GMP Basics

Profiling
=========

   Running a program under a profiler is a good way to find where it's
spending most time and where improvements can be best sought.

   Depending on the system, it may be possible to get a flat profile,
meaning simple timer sampling of the program counter, with no special
GMP build options, just a `-p' when compiling the mainline.  This is a
good way to ensure minimum interference with normal operation.  The
necessary symbol type and size information exists in most of the GMP
assembler code.

   The `--enable-profiling' build option can be used to add suitable
compiler flags, either for `prof' (`-p') or `gprof' (`-pg'), see *Note
Build Options::.  Which of the two is available and what they do will
depend on the system, and possibly on support available in `libc'.  For
some systems appropriate corresponding `mcount' calls are added to the
assembler code too.

   On x86 systems `prof' gives call counting, so that average time spent
in a function can be determined.  `gprof', where supported, adds call
graph construction, so for instance calls to `mpn_add_n' from `mpz_add'
and from `mpz_mul' can be differentiated.

   On x86 and 68k systems `-pg' and `-fomit-frame-pointer' are
incompatible, so the latter is not used when `gprof' profiling is
selected, which may result in poorer code generation.  If `prof'
profiling is selected instead it should still be possible to use
`gprof', but only the `gprof -p' flat profile and call counts can be
expected to be valid, not the `gprof -q' call graph.


File: gmp.info,  Node: Autoconf,  Prev: Profiling,  Up: GMP Basics

Autoconf
========

   Autoconf based applications can easily check whether GMP is
installed.  The only thing to be noted is that GMP library symbols from
version 3 onwards have prefixes like `__gmpz'.  The following therefore
would be a simple test,

     AC_CHECK_LIB(gmp, __gmpz_init)

   This just uses the default `AC_CHECK_LIB' actions for found or not
found, but an application that must have GMP would want to generate an
error if not found.  For example,

     AC_CHECK_LIB(gmp, __gmpz_init, , [AC_MSG_ERROR(
     [GNU MP not found, see http://swox.com/gmp])])

   If functions added in some particular version of GMP are required,
then one of those can be used when checking.  For example `mpz_mul_si'
was added in GMP 3.1,

     AC_CHECK_LIB(gmp, __gmpz_mul_si, , [AC_MSG_ERROR(
     [GNU MP not found, or not 3.1 or up, see http://swox.com/gmp])])

   An alternative would be to test the version number in `gmp.h' using
say `AC_EGREP_CPP'.  That would make it possible to test the exact
version, if some particular sub-minor release is known to be necessary.

   An application that can use either GMP 2 or 3 will need to test for
`__gmpz_init' (GMP 3 and up) or `mpz_init' (GMP 2), and it's also worth
checking for `libgmp2' since Debian GNU/Linux systems used that name in
the past.  For example,

     AC_CHECK_LIB(gmp, __gmpz_init, ,
       [AC_CHECK_LIB(gmp, mpz_init, ,
         [AC_CHECK_LIB(gmp2, mpz_init)])])

   In general it's suggested that applications should simply demand a
new enough GMP rather than trying to provide supplements for features
not available in past versions.

   Occasionally an application will need or want to know the size of a
type at configuration or preprocessing time, not just with `sizeof' in
the code.  This can be done in the normal way with `mp_limb_t' etc, but
GMP 4.0 or up is best for this, since prior versions needed certain
`-D' defines on systems using a `long long' limb.  The following would
suit Autoconf 2.50 or up,

     AC_CHECK_SIZEOF(mp_limb_t, , [#include <gmp.h>])

   The optional `mpfr' functions are provided in a separate
`libmpfr.a', and this might be from GMP with `--enable-mpfr' or from
MPFR installed separately.  Either way `libmpfr' depends on `libgmp',
it doesn't stand alone.  Currently only a static `libmpfr.a' will be
available, not a shared library, since upward binary compatibility is
not guaranteed.

     AC_CHECK_LIB(mpfr, mpfr_add, , [AC_MSG_ERROR(
     [Need MPFR either from GNU MP 4 or separate MPFR package.
     See http://www.mpfr.org or http://swox.com/gmp])


File: gmp.info,  Node: Reporting Bugs,  Next: Integer Functions,  Prev: GMP Basics,  Up: Top

Reporting Bugs
**************

   If you think you have found a bug in the GMP library, please
investigate it and report it.  We have made this library available to
you, and it is not too much to ask you to report the bugs you find.

   Before you report a bug, check it's not already addressed in *Note
Known Build Problems::, or perhaps *Note Notes for Particular
Systems::.  You may also want to check `http://swox.com/gmp/' for
patches for this release.

   Please include the following in any report,

   * The GMP version number, and if pre-packaged or patched then say so.

   * A test program that makes it possible for us to reproduce the bug.
     Include instructions on how to run the program.

   * A description of what is wrong.  If the results are incorrect, in
     what way.  If you get a crash, say so.

   * If you get a crash, include a stack backtrace from the debugger if
     it's informative (`where' in `gdb', or `$C' in `adb').

   * Please do not send core dumps, executables or `strace's.

   * The configuration options you used when building GMP, if any.

   * The name of the compiler and its version.  For `gcc', get the
     version with `gcc -v', otherwise perhaps `what `which cc`', or
     similar.

   * The output from running `uname -a'.

   * The output from running `./config.guess', and from running
     `./configfsf.guess' (might be the same).

   * If the bug is related to `configure', then the contents of
     `config.log'.

   * If the bug is related to an `asm' file not assembling, then the
     contents of `config.m4' and the offending line or lines from the
     temporary `mpn/tmp-<file>.s'.

   Please make an effort to produce a self-contained report, with
something definite that can be tested or debugged.  Vague queries or
piecemeal messages are difficult to act on and don't help the
development effort.

   It is not uncommon that an observed problem is actually due to a bug
in the compiler; the GMP code tends to explore interesting corners in
compilers.

   If your bug report is good, we will do our best to help you get a
corrected version of the library; if the bug report is poor, we won't
do anything about it (except maybe ask you to send a better report).

   Send your report to: <bug-gmp@gnu.org>.

   If you think something in this manual is unclear, or downright
incorrect, or if the language needs to be improved, please send a note
to the same address.


File: gmp.info,  Node: Integer Functions,  Next: Rational Number Functions,  Prev: Reporting Bugs,  Up: Top

Integer Functions
*****************

   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'.

* Menu:

* Initializing Integers::
* Assigning Integers::
* Simultaneous Integer Init & Assign::
* Converting Integers::
* Integer Arithmetic::
* Integer Division::
* Integer Exponentiation::
* Integer Roots::
* Number Theoretic Functions::
* Integer Comparisons::
* Integer Logic and Bit Fiddling::
* I/O of Integers::
* Integer Random Numbers::
* Miscellaneous Integer Functions::


File: gmp.info,  Node: Initializing Integers,  Next: Assigning Integers,  Prev: Integer Functions,  Up: Integer Functions

Initialization Functions
========================

   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.

 - Function: void mpz_init (mpz_t INTEGER)
     Initialize INTEGER, and set its value to 0.

 - Function: void mpz_init2 (mpz_t INTEGER, unsigned long N)
     Initialize INTEGER, with space for N bits, and set its value to 0.

     N is only the initial space, INTEGER 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.

 - Function: void mpz_clear (mpz_t INTEGER)
     Free the space occupied by INTEGER.  Call this function for all
     `mpz_t' variables when you are done with them.

 - Function: void mpz_realloc2 (mpz_t INTEGER, unsigned long N)
     Change the space allocated for INTEGER to N bits.  The value in
     INTEGER is preserved if it fits, or is set to 0 if not.

     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.

 - Function: void mpz_array_init (mpz_t INTEGER_ARRAY[], size_t
          ARRAY_SIZE, mp_size_t FIXED_NUM_BITS)
     This is a special type of initialization.  *Fixed* space of
     FIXED_NUM_BITS bits is allocated to each of the ARRAY_SIZE
     integers in INTEGER_ARRAY.

     The space will not be automatically increased, unlike the normal
     `mpz_init', but instead an application must ensure it's sufficient
     for any value stored.  The following space requirements apply to
     various functions,

        * `mpz_abs', `mpz_neg', `mpz_set', `mpz_set_si' and
          `mpz_set_ui' need room for the value they store.

        * `mpz_add', `mpz_add_ui', `mpz_sub' and `mpz_sub_ui' need room
          for the larger of the two operands, plus an extra
          `mp_bits_per_limb'.

        * `mpz_mul', `mpz_mul_ui' and `mpz_mul_ui' need room for the sum
          of the number of bits in their operands, but each rounded up
          to a multiple of `mp_bits_per_limb'.

        * `mpz_swap' can be used between two array variables, but not
          between an array and a normal variable.

     For other functions, or if in doubt, the suggestion is to
     calculate in a regular `mpz_init' variable and copy the result to
     an array variable with `mpz_set'.

     `mpz_array_init' can reduce memory usage in algorithms that need
     large arrays of integers, since it avoids allocating and
     reallocating lots of small memory blocks.  There is no way to free
     the storage allocated by this function.  Don't call `mpz_clear'!

 - Function: void * _mpz_realloc (mpz_t INTEGER, mp_size_t NEW_ALLOC)
     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 the new size in limbs.


File: gmp.info,  Node: Assigning Integers,  Next: Simultaneous Integer Init & Assign,  Prev: Initializing Integers,  Up: Integer Functions

Assignment Functions
====================

   These functions assign new values to already initialized integers
(*note Initializing Integers::).

 - Function: void mpz_set (mpz_t ROP, mpz_t OP)
 - Function: void mpz_set_ui (mpz_t ROP, unsigned long int OP)
 - Function: void mpz_set_si (mpz_t ROP, signed long int OP)
 - Function: void mpz_set_d (mpz_t ROP, double OP)
 - Function: void mpz_set_q (mpz_t ROP, mpq_t OP)
 - Function: void mpz_set_f (mpz_t ROP, mpf_t OP)
     Set the value of ROP from OP.

     `mpz_set_d', `mpz_set_q' and `mpz_set_f' truncate OP to make it an
     integer.

 - Function: int mpz_set_str (mpz_t ROP, char *STR, int BASE)
     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 36.  If BASE is 0, the
     actual base is determined from the leading characters: if the
     first two characters are "0x" or "0X", hexadecimal is assumed,
     otherwise if the first character is "0", octal is assumed,
     otherwise decimal is assumed.

     This function returns 0 if the entire string is a valid number in
     base BASE.  Otherwise it returns -1.

     [It turns out that it is not entirely true that this function
     ignores white-space.  It does ignore it between digits, but not
     after a minus sign or within or after "0x".  We are considering
     changing the definition of this function, making it fail when
     there is any white-space in the input, since that makes a lot of
     sense.  Send your opinion of this change to <bug-gmp@gnu.org>.  Do
     you really want it to accept "3 14" as meaning 314 as it does now?]

 - Function: void mpz_swap (mpz_t ROP1, mpz_t ROP2)
     Swap the values ROP1 and ROP2 efficiently.


File: gmp.info,  Node: Simultaneous Integer Init & Assign,  Next: Converting Integers,  Prev: Assigning Integers,  Up: Integer Functions

Combined Initialization and Assignment Functions
================================================

   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!

 - Function: void mpz_init_set (mpz_t ROP, mpz_t OP)
 - Function: void mpz_init_set_ui (mpz_t ROP, unsigned long int OP)
 - Function: void mpz_init_set_si (mpz_t ROP, signed long int OP)
 - Function: void mpz_init_set_d (mpz_t ROP, double OP)
     Initialize ROP with limb space and set the initial numeric value
     from OP.

 - Function: int mpz_init_set_str (mpz_t ROP, char *STR, int BASE)
     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.)


File: gmp.info,  Node: Converting Integers,  Next: Integer Arithmetic,  Prev: Simultaneous Integer Init & Assign,  Up: Integer Functions

Conversion Functions
====================

   This section describes functions for converting GMP integers to
standard C types.  Functions for converting _to_ GMP integers are
described in *Note Assigning Integers:: and *Note I/O of Integers::.

 - Function: unsigned long int mpz_get_ui (mpz_t OP)
     Return the least significant part from OP.  This function combined
     with
     `mpz_tdiv_q_2exp(..., OP, CHAR_BIT*sizeof(unsigned long int))' can
     be used to decompose an integer into unsigned longs.

 - Function: signed long int mpz_get_si (mpz_t OP)
     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 large 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'.

 - Function: double mpz_get_d (mpz_t OP)
     Convert OP to a `double'.

 - Function: double mpz_get_d_2exp (signed long int EXP, mpz_t OP)
     Find D and EXP such that D times 2 raised to EXP, with
     0.5<=abs(D)<1, is a good approximation to OP.

 - Function: char * mpz_get_str (char *STR, int BASE, mpz_t OP)
     Convert OP to a string of digits in base BASE.  The base may vary
     from 2 to 36.

     If STR is `NULL', the result string is allocated using the current
     allocation function (*note 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.

 - Function: mp_limb_t mpz_getlimbn (mpz_t OP, mp_size_t N)
     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'.


File: gmp.info,  Node: Integer Arithmetic,  Next: Integer Division,  Prev: Converting Integers,  Up: Integer Functions

Arithmetic Functions
====================

 - Function: void mpz_add (mpz_t ROP, mpz_t OP1, mpz_t OP2)
 - Function: void mpz_add_ui (mpz_t ROP, mpz_t OP1, unsigned long int
          OP2)
     Set ROP to OP1 + OP2.

 - Function: void mpz_sub (mpz_t ROP, mpz_t OP1, mpz_t OP2)
 - Function: void mpz_sub_ui (mpz_t ROP, mpz_t OP1, unsigned long int
          OP2)
     Set ROP to OP1 - OP2.

 - Function: void mpz_mul (mpz_t ROP, mpz_t OP1, mpz_t OP2)
 - Function: void mpz_mul_si (mpz_t ROP, mpz_t OP1, long int OP2)
 - Function: void mpz_mul_ui (mpz_t ROP, mpz_t OP1, unsigned long int
          OP2)
     Set ROP to OP1 times OP2.

 - Function: void mpz_addmul (mpz_t ROP, mpz_t OP1, mpz_t OP2)
 - Function: void mpz_addmul_ui (mpz_t ROP, mpz_t OP1, unsigned long
          int OP2)
     Set ROP to ROP + OP1 times OP2.

 - Function: void mpz_submul (mpz_t ROP, mpz_t OP1, mpz_t OP2)
 - Function: void mpz_submul_ui (mpz_t ROP, mpz_t OP1, unsigned long
          int OP2)
     Set ROP to ROP - OP1 times OP2.

 - Function: void mpz_mul_2exp (mpz_t ROP, mpz_t OP1, unsigned long int
          OP2)
     Set ROP to OP1 times 2 raised to OP2.  This operation can also be
     defined as a left shift by OP2 bits.

 - Function: void mpz_neg (mpz_t ROP, mpz_t OP)
     Set ROP to -OP.

 - Function: void mpz_abs (mpz_t ROP, mpz_t OP)
     Set ROP to the absolute value of OP.


File: gmp.info,  Node: Integer Division,  Next: Integer Exponentiation,  Prev: Integer Arithmetic,  Up: Integer Functions

Division Functions
==================

   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.

 - Function: void mpz_cdiv_q (mpz_t Q, mpz_t N, mpz_t D)
 - Function: void mpz_cdiv_r (mpz_t R, mpz_t N, mpz_t D)
 - Function: void mpz_cdiv_qr (mpz_t Q, mpz_t R, mpz_t N, mpz_t D)
 - Function: unsigned long int mpz_cdiv_q_ui (mpz_t Q, mpz_t N,
          unsigned long int D)
 - Function: unsigned long int mpz_cdiv_r_ui (mpz_t R, mpz_t N,
          unsigned long int D)
 - Function: unsigned long int mpz_cdiv_qr_ui (mpz_t Q, mpz_t R,
          mpz_t N, unsigned long int D)
 - Function: unsigned long int mpz_cdiv_ui (mpz_t N,
          unsigned long int D)
 - Function: void mpz_cdiv_q_2exp (mpz_t Q, mpz_t N,
          unsigned long int B)
 - Function: void mpz_cdiv_r_2exp (mpz_t R, mpz_t N,
          unsigned long int B)

 - Function: void mpz_fdiv_q (mpz_t Q, mpz_t N, mpz_t D)
 - Function: void mpz_fdiv_r (mpz_t R, mpz_t N, mpz_t D)
 - Function: void mpz_fdiv_qr (mpz_t Q, mpz_t R, mpz_t N, mpz_t D)
 - Function: unsigned long int mpz_fdiv_q_ui (mpz_t Q, mpz_t N,
          unsigned long int D)
 - Function: unsigned long int mpz_fdiv_r_ui (mpz_t R, mpz_t N,
          unsigned long int D)
 - Function: unsigned long int mpz_fdiv_qr_ui (mpz_t Q, mpz_t R,
          mpz_t N, unsigned long int D)
 - Function: unsigned long int mpz_fdiv_ui (mpz_t N,
          unsigned long int D)
 - Function: void mpz_fdiv_q_2exp (mpz_t Q, mpz_t N,
          unsigned long int B)
 - Function: void mpz_fdiv_r_2exp (mpz_t R, mpz_t N,
          unsigned long int B)

 - Function: void mpz_tdiv_q (mpz_t Q, mpz_t N, mpz_t D)
 - Function: void mpz_tdiv_r (mpz_t R, mpz_t N, mpz_t D)
 - Function: void mpz_tdiv_qr (mpz_t Q, mpz_t R, mpz_t N, mpz_t D)
 - Function: unsigned long int mpz_tdiv_q_ui (mpz_t Q, mpz_t N,
          unsigned long int D)
 - Function: unsigned long int mpz_tdiv_r_ui (mpz_t R, mpz_t N,
          unsigned long int D)
 - Function: unsigned long int mpz_tdiv_qr_ui (mpz_t Q, mpz_t R,
          mpz_t N, unsigned long int D)
 - Function: unsigned long int mpz_tdiv_ui (mpz_t N,
          unsigned long int D)
 - Function: void mpz_tdiv_q_2exp (mpz_t Q, mpz_t N,
          unsigned long int B)
 - Function: void mpz_tdiv_r_2exp (mpz_t R, mpz_t N,
          unsigned long int B)

     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.

     The `2exp' functions are right shifts and bit masks, but of course
     rounding 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.

 - Function: void mpz_mod (mpz_t R, mpz_t N, mpz_t D)
 - Function: unsigned long int mpz_mod_ui (mpz_t R, mpz_t N,
          unsigned long int D)
     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.

 - Function: void mpz_divexact (mpz_t Q, mpz_t N, mpz_t D)
 - Function: void mpz_divexact_ui (mpz_t Q, mpz_t N, unsigned long D)
     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.

 - Function: int mpz_divisible_p (mpz_t N, mpz_t D)
 - Function: int mpz_divisible_ui_p (mpz_t N, unsigned long int D)
 - Function: int mpz_divisible_2exp_p (mpz_t N, unsigned long int B)
     Return non-zero if N is exactly divisible by D, or in the case of
     `mpz_divisible_2exp_p' by 2^B.

 - Function: int mpz_congruent_p (mpz_t N, mpz_t C, mpz_t D)
 - Function: int mpz_congruent_ui_p (mpz_t N, unsigned long int C,
          unsigned long int D)
 - Function: int mpz_congruent_2exp_p (mpz_t N, mpz_t C, unsigned long
          int B)
     Return non-zero if N is congruent to C modulo D, or in the case of
     `mpz_congruent_2exp_p' modulo 2^B.


File: gmp.info,  Node: Integer Exponentiation,  Next: Integer Roots,  Prev: Integer Division,  Up: Integer Functions

Exponentiation Functions
========================

 - Function: void mpz_powm (mpz_t ROP, mpz_t BASE, mpz_t EXP, mpz_t MOD)
 - Function: void mpz_powm_ui (mpz_t ROP, mpz_t BASE, unsigned long int
          EXP, mpz_t MOD)
     Set ROP to (BASE raised to EXP) modulo MOD.

     Negative EXP is supported if an inverse BASE^-1 mod MOD exists
     (see `mpz_invert' in *Note Number Theoretic Functions::).  If an
     inverse doesn't exist then a divide by zero is raised.

 - Function: void mpz_pow_ui (mpz_t ROP, mpz_t BASE, unsigned long int
          EXP)
 - Function: void mpz_ui_pow_ui (mpz_t ROP, unsigned long int BASE,
          unsigned long int EXP)
     Set ROP to BASE raised to EXP.  The case 0^0 yields 1.


File: gmp.info,  Node: Integer Roots,  Next: Number Theoretic Functions,  Prev: Integer Exponentiation,  Up: Integer Functions

Root Extraction Functions
=========================

 - Function: int mpz_root (mpz_t ROP, mpz_t OP, unsigned long int N)
     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.

 - Function: void mpz_sqrt (mpz_t ROP, mpz_t OP)
     Set ROP to  the truncated integer part of the square root of OP.

 - Function: void mpz_sqrtrem (mpz_t ROP1, mpz_t ROP2, mpz_t 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.

 - Function: int mpz_perfect_power_p (mpz_t OP)
     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.

 - Function: int mpz_perfect_square_p (mpz_t OP)
     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.


File: gmp.info,  Node: Number Theoretic Functions,  Next: Integer Comparisons,  Prev: Integer Roots,  Up: Integer Functions

Number Theoretic Functions
==========================

 - Function: int mpz_probab_prime_p (mpz_t N, int REPS)
     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 composite.

     This function does some trial divisions, then some Miller-Rabin
     probabilistic primality tests.  REPS controls how many such tests
     are done, 5 to 10 is a reasonable number, more will reduce the
     chances of a composite being returned as "probably prime".

     Miller-Rabin and similar tests can be more properly called
     compositeness tests.  Numbers which fail are known to be composite
     but those which pass might be prime or might be composite.  Only a
     few composites pass, hence those which pass are considered
     probably prime.

 - Function: void mpz_nextprime (mpz_t ROP, mpz_t OP)
     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.

 - Function: void mpz_gcd (mpz_t ROP, mpz_t OP1, mpz_t OP2)
     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.

 - Function: unsigned long int mpz_gcd_ui (mpz_t ROP, mpz_t OP1,
          unsigned long int OP2)
     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.

 - Function: void mpz_gcdext (mpz_t G, mpz_t S, mpz_t T, mpz_t A, mpz_t
          B)
     Compute G, S, and T, such that A*S + B*T = G = gcd(A, B).  If T is
     `NULL', that argument is not computed.

 - Function: void mpz_lcm (mpz_t ROP, mpz_t OP1, mpz_t OP2)
 - Function: void mpz_lcm_ui (mpz_t ROP, mpz_t OP1, unsigned long OP2)
     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.

 - Function: int mpz_invert (mpz_t ROP, mpz_t OP1, mpz_t OP2)
     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 < OP2.  If an inverse doesn't exist the return
     value is zero and ROP is undefined.

 - Function: int mpz_jacobi (mpz_t A, mpz_t B)
     Calculate the Jacobi symbol (A/B).  This is defined only for B odd.

 - Function: int mpz_legendre (mpz_t A, mpz_t P)
     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.

 - Function: int mpz_kronecker (mpz_t A, mpz_t B)
 - Function: int mpz_kronecker_si (mpz_t A, long B)
 - Function: int mpz_kronecker_ui (mpz_t A, unsigned long B)
 - Function: int mpz_si_kronecker (long A, mpz_t B)
 - Function: int mpz_ui_kronecker (unsigned long A, mpz_t B)
     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 (*note
     References::), or any number theory textbook.  See also the
     example program `demos/qcn.c' which uses `mpz_kronecker_ui'.

 - Function: unsigned long int mpz_remove (mpz_t ROP, mpz_t OP, mpz_t F)
     Remove all occurrences of the factor F from OP and store the
     result in ROP.  Return the multiplicity of F in OP.

 - Function: void mpz_fac_ui (mpz_t ROP, unsigned long int OP)
     Set ROP to OP!, the factorial of OP.

 - Function: void mpz_bin_ui (mpz_t ROP, mpz_t N, unsigned long int K)
 - Function: void mpz_bin_uiui (mpz_t ROP, unsigned long int N,
          unsigned long int K)
     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.

 - Function: void mpz_fib_ui (mpz_t FN, unsigned long int N)
 - Function: void mpz_fib2_ui (mpz_t FN, mpz_t FNSUB1, unsigned long
          int N)
     `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.

 - Function: void mpz_lucnum_ui (mpz_t LN, unsigned long int N)
 - Function: void mpz_lucnum2_ui (mpz_t LN, mpz_t LNSUB1, unsigned long
          int N)
     `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 *Note Lucas Numbers Algorithm::, the reverse is
     straightforward too.


File: gmp.info,  Node: Integer Comparisons,  Next: Integer Logic and Bit Fiddling,  Prev: Number Theoretic Functions,  Up: Integer Functions

Comparison Functions
====================

 - Function: int mpz_cmp (mpz_t OP1, mpz_t OP2)
 - Function: int mpz_cmp_d (mpz_t OP1, double OP2)
 - Macro: int mpz_cmp_si (mpz_t OP1, signed long int OP2)
 - Macro: int mpz_cmp_ui (mpz_t OP1, unsigned long int OP2)
     Compare OP1 and OP2.  Return a positive value if OP1 > OP2, zero
     if OP1 = OP2, or a negative value if OP1 < OP2.

     Note that `mpz_cmp_ui' and `mpz_cmp_si' are macros and will
     evaluate their arguments more than once.

 - Function: int mpz_cmpabs (mpz_t OP1, mpz_t OP2)
 - Function: int mpz_cmpabs_d (mpz_t OP1, double OP2)
 - Function: int mpz_cmpabs_ui (mpz_t OP1, unsigned long int OP2)
     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).

     Note that `mpz_cmpabs_si' is a macro and will evaluate its
     arguments more than once.

 - Macro: int mpz_sgn (mpz_t OP)
     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.


File: gmp.info,  Node: Integer Logic and Bit Fiddling,  Next: I/O of Integers,  Prev: Integer Comparisons,  Up: Integer Functions

Logical and Bit Manipulation Functions
======================================

   These functions behave as if twos complement arithmetic were used
(although sign-magnitude is the actual implementation).  The least
significant bit is number 0.

 - Function: void mpz_and (mpz_t ROP, mpz_t OP1, mpz_t OP2)
     Set ROP to OP1 logical-and OP2.

 - Function: void mpz_ior (mpz_t ROP, mpz_t OP1, mpz_t OP2)
     Set ROP to OP1 inclusive-or OP2.

 - Function: void mpz_xor (mpz_t ROP, mpz_t OP1, mpz_t OP2)
     Set ROP to OP1 exclusive-or OP2.

 - Function: void mpz_com (mpz_t ROP, mpz_t OP)
     Set ROP to the one's complement of OP.

 - Function: unsigned long int mpz_popcount (mpz_t 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 MAX_ULONG, the largest
     possible `unsigned long'.

 - Function: unsigned long int mpz_hamdist (mpz_t OP1, mpz_t OP2)
     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 MAX_ULONG, the largest
     possible `unsigned long'.

 - Function: unsigned long int mpz_scan0 (mpz_t OP, unsigned long int
          STARTING_BIT)
 - Function: unsigned long int mpz_scan1 (mpz_t OP, unsigned long int
          STARTING_BIT)
     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 MAX_ULONG is returned.  This will
     happen in `mpz_scan0' past the end of a positive number, or
     `mpz_scan1' past the end of a negative.

 - Function: void mpz_setbit (mpz_t ROP, unsigned long int BIT_INDEX)
     Set bit BIT_INDEX in ROP.

 - Function: void mpz_clrbit (mpz_t ROP, unsigned long int BIT_INDEX)
     Clear bit BIT_INDEX in ROP.

 - Function: int mpz_tstbit (mpz_t OP, unsigned long int BIT_INDEX)
     Test bit BIT_INDEX in OP and return 0 or 1 accordingly.

