This is gmp.info, produced by makeinfo version 4.0 from gmp.texi. START-INFO-DIR-ENTRY * gmp: (gmp.info). GNU Multiple Precision Arithmetic Library. END-INFO-DIR-ENTRY This file documents GNU MP, a library for arbitrary-precision arithmetic. Copyright (C) 1991, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Foundation.  File: gmp.info, Node: Top, Next: Copying, Prev: (dir), Up: (dir) GNU MP ****** This manual documents how to install and use the GNU multiple precision arithmetic library, version 3.0. * Menu: * Copying:: GMP Copying Conditions (LGPL). * Introduction to GMP:: Brief introduction to GNU MP. * Installing GMP:: How to configure and compile the GMP library. * GMP Basics:: What every GMP user should now. * Reporting Bugs:: How to usefully report bugs. * Integer Functions:: Functions for arithmetic on signed integers. * Rational Number Functions:: Functions for arithmetic on rational numbers. * Floating-point Functions:: Functions for arithmetic on floats. * Low-level Functions:: Fast functions for natural numbers. * Random Number Functions:: Functions for generating random numbers. * BSD Compatible Functions:: All functions found in BSD MP. * Custom Allocation:: How to customize the internal allocation. * Contributors:: Who brings your this library? * References:: Some useful papers and books to read. * Concept Index:: * Function Index::  File: gmp.info, Node: Copying, Next: Introduction to GMP, Prev: Top, Up: Top GNU MP Copying Conditions ************************* This library is "free"; this means that everyone is free to use it and free to redistribute it on a free basis. The library is not in the public domain; it is copyrighted and there are restrictions on its distribution, but these restrictions are designed to permit everything that a good cooperating citizen would want to do. What is not allowed is to try to prevent others from further sharing any version of this library that they might get from you. Specifically, we want to make sure that you have the right to give away copies of the library, that you receive source code or else can get it if you want it, that you can change this library or use pieces of it in new free programs, and that you know you can do these things. To make sure that everyone has such rights, we have to forbid you to deprive anyone else of these rights. For example, if you distribute copies of the GNU MP library, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. Also, for our own protection, we must make certain that everyone finds out that there is no warranty for the GNU MP library. If it is modified by someone else and passed on, we want their recipients to know that what they have is not what we distributed, so that any problems introduced by others will not reflect on our reputation. The precise conditions of the license for the GNU MP library are found in the Library General Public License that accompany the source code.  File: gmp.info, Node: Introduction to GMP, Next: Installing GMP, Prev: Copying, Up: Top Introduction to GNU MP ********************** GNU MP is a portable library written in C for arbitrary precision arithmetic on integers, rational numbers, and floating-point numbers. It aims to provide the fastest possible arithmetic for all applications that need higher precision than is directly supported by the basic C types. Many applications use just a few hundred bits of precision; but some applications may need thousands or even millions of bits. GMP is designed to give good performance for both, by choosing algorithms based on the sizes of the operands, and by carefully keeping the overhead at a minimum. The speed of GMP is achieved by using fullwords as the basic arithmetic type, by using sophisticated algorithms, by including carefully optimized assembly code for the most common inner loops for many different CPUs, and by a general emphasis on speed (as opposed to simplicity or elegance). There is carefully optimized assembly code for these CPUs: ARM, DEC Alpha 21064, 21164, and 21264, AMD 29000, K6 and Athlon, Hitachi SH and SH2, HPPA 1.0, 1.1 and 2.0, Intel Pentium, Pentium Pro/Pentium II, generic x86, Intel i960, Motorola MC68000, MC68020, MC88100, and MC88110, Motorola/IBM PowerPC 32 and 64, National NS32000, IBM POWER, MIPS R3000, R4000, SPARCv7, SuperSPARC, generic SPARCv8, UltraSPARC, DEC VAX, and Zilog Z8000. Some optimizations also for Clipper, IBM ROMP (RT), and Pyramid AP/XP. There is a mailing list for GMP users. To join it, send a mail to with the word `subscribe' in the message *body* (not in the subject line). For up-to-date information on GMP, please see the GMP Home Pages at `http://www.swox.com/gmp/'. How to use this Manual ====================== Everyone should read *Note GMP Basics::. If you need to install the library yourself, you need to read *Note Installing GMP::, too. The rest of the manual can be used for later reference, although it is probably a good idea to glance through it.  File: gmp.info, Node: Installing GMP, Next: GMP Basics, Prev: Introduction to GMP, Up: Top Installing GMP ************** GMP has an autoconf/automake/libtool based configuration system. On a Unix-like system a basic build can be done with ./configure make Some self-tests can be run with make check And you can install (under `/usr/local' by default) with make install If you experience problems, please report them to . (*Note Reporting Bugs::, for information on what to include in useful bug reports.) Build Options ============= All the usual autoconf configure options are available, run `./configure --help' for a summary. Non-Unix Systems `configure' needs various Unix-like tools installed. On an MS-DOS system cygwin or djgpp should work. It might be possible to build without the help of `configure', certainly all the code is there, but you'll be on your own. Object Directory To compile in a separate object directory, `cd' to that directory, and prefix the configure command with the path to the GMP source directory. Not all `make' programs have the necessary features (`VPATH') to support this. In particular, SunOS and Slowaris `make' have bugs that make them unable to build from a separate object directory. Use GNU `make' instead. `--disable-shared', `--disable-static' By default both shared and static libraries are built (where possible), but one or other can be disabled. Shared libraries are very slightly slower, having a small cost on each function call, but result in smaller executables and permit code sharing between separate running processes. `--target=CPU-VENDOR-OS' The build target can be specified in the usual way, for either native or cross compilation. If `--target' isn't given, `./configure' builds for the host system. On some systems `./configure' can't distinguish between different CPUs in a family, and you should check its guess (run `./config.guess' to see it). In general, if you want a library that runs as fast as possible, you should configure GMP for the exact CPU type your system uses. However, this may mean the binaries won't run on older members of the family, and might run slower on other members, older or newer. The best idea is always to build GMP for the exact machine type you intend to run it on. If you need to create binaries that will run on several processors in a family, GMP should be configured for the lowest common denominator among them, something with which all the desired processors are upwardly compatible. The following CPUs have specific assembly code support. See `configure.in' for which `mpn' subdirectories get used by each. * Alpha: `alpha', `alphaev5', `alphaev6' * Cray: `cray2', `xmp', `ymp' * Fujitsu: `f301' * Hitachi: `sh', `sh2' * HPPA: `hppa1.0', `hppa1.1', `hppa2.0' * MIPS: `mips', `mips3', * Motorola: `m68000', `m68k', `m88k', `m88110' * POWER: `power', `rs6000', `powerpc', `powerpc64' * Sparc: `sparc', `sparcv8', `microsparc', `supersparc', `sparcv9', `ultrasparc', `sparc64' * 80x86 family: `i386', `i486', `i586', `pentium', `pentiummmx', `pentiumpro', `pentium2', `pentium3', `k6', `k62', `k63', `athlon' * Other: `a29k', `arm', `clipper', `i960', `ns32k', `pyramid', `vax', `z8k' CPUs not listed use generic C code. If some of the assembly code causes problems, the generic C code can be selected with CPU `none'. `CC', `CFLAGS' The C compiler used is chosen from among some likely candidates, with GCC normally preferred if it's present. The usual `CC=whatever' can be passed to `./configure' to choose something different. For some configurations specific compiler flags are set based on the target CPU and compiler, for others `CFLAGS="-whatever"' can be used to choose the best flags. `--disable-alloca' By default, GMP allocates temporary workspace using `alloca' if that function is available, or `malloc' if not. If you're working with large numbers and `alloca' overflows the available stack space, you can build with `--disable-alloca' to use `malloc' instead. `malloc' will probably be slightly slower than `alloca'. When not using `alloca', it's actually the allocation function selected with `mp_set_memory_functions' that's used, this being `malloc' by default. *Note Custom Allocation::. Depending on your system, the only indication of stack overflow might be a segmentation violation. `limit', `ulimit' or `setrlimit' might be able to increase the stack space available to programs. `--enable-mpbsd' The Berkeley MP compatibility library (`libmp.a') and header file (`mp.h') are built and installed only if `--enable-mpbsd' is used. *Note BSD Compatible Functions::. Demonstration Programs The `demos' subdirectory has some sample programs using GMP. These aren't built or installed, but there's a `Makefile' with rules for them. For instance, `make pexpr' and then `./pexpr 68^975+10'. Documentation The document you're now reading is `gmp.texi'. The usual automake targets are available to make `gmp.ps' and/or `gmp.dvi'. Notes for Particular Systems ============================ AIX Targets `*-*-aix*' have shared libraries disabled since they seem to fail on AIX 4.3. AIX with PowerPC 64 Currently only a 64-bit version of the GMP library is built, and when linking your application you need to pass `-maix64' to `gcc' or `-q64' to `xlc'. We hope this will change in a future version of GMP. HPPA The GMP assembly code for HPPA is not currently position-independent, so shared libraries are disabled for targets `hppa*-*-*'. Sparc Using `sparcv8' or `supersparc' for the target CPU will give a significant performance increase on relevant systems. x86 Pentium and PentiumPro The Intel Pentium P5 code is good for its intended P5, but quite slow when run on Intel P6 class chips (PPro, P-II, P-III). `i386' is a better choice if you're making binaries that must run on both. x86 MMX and old GAS Old versions of GAS don't support MMX instructions, in particular version 1.92.3 that comes with FreeBSD 2.2.8 doesn't (and unfortunately there's no newer assembler for that system). If the target CPU has MMX code but the assembler doesn't support it, a warning is given and non-MMX code is used instead. This will be an inferior build, since the MMX code that's present is there because it's faster than the corresponding plain integer code. Known Build Problems ==================== You might find more up-to-date information at `http://www.swox.com/gmp/'. NeXT prior to 3.3 The system compiler on old versions of NeXT was a massacred and old GCC, even if the compiler called itself `cc'. This compiler cannot be used to build GMP, you need to get a real GCC, and install that before you compile GMP. (NeXT may have fixed this in release 3.3 of their system.) POWER and PowerPC Bugs in GCC 2.7.2 (and 2.6.3) mean it can't be used to compile GMP on POWER or PowerPC. If you want to use GCC for these machines, get GCC 2.7.2.1 (or later). Sequent Symmetry Use the GNU assembler instead of the system assembler, since the latter has serious bugs. SunOS 4 The system C compiler has a bug that makes it miscompile `mpq/get_d.c' and `mpf/get_d.c', and causes two corresponding tests to fail. (You can `cd' to the `mpz' directory to run `make check' there to test the rest of the build.) Use GCC instead if you plan to use the function `mpq_get_d'. `/usr/bin/m4' lacks features needed to process `.asm' files. Either the SysV `/usr/5bin/m4' or GNU `m4' should be used instead. On the `./configure' command line use `M4=/usr/5bin/m4', or the equivalent for wherever GNU `m4' is installed. The setting for `GSYM_PREFIX' in `config.m4' may be incorrectly determined when using the native `grep', leading at link-time to undefined symbols like `___gmpn_add_n'. To fix this, after running `./configure', change the relevant line in `config.m4' to `define(, <_>)'. The `ranlib' command will need to be run manually when building a static library with the native `ar'. After `make', run `ranlib .libs/libgmp.a', and when using `--enable-mpbsd' run `ranlib .libs/libmp.a' too. VAX running Ultrix You need to build and install the GNU assembler before you compile GMP. The VAX assembly in GMP uses an instruction (`jsobgtr') that cannot be assembled by the Ultrix assembler.  File: gmp.info, Node: GMP Basics, Next: Reporting Bugs, Prev: Installing GMP, Up: Top GMP Basics ********** All declarations needed to use GMP are collected in the include file `gmp.h'. It is designed to work with both C and C++ compilers. *Using functions, macros, data types, etc. not documented in this manual is strongly discouraged. If you do so your application is guaranteed to be incompatible with future versions of GMP.* * Menu: * Nomenclature and Types:: Which data types are there? * Function Classes:: How the functions are organized. * GMP Variable Conventions:: Some rules and hints about variables. * GMP and reentrancy:: What about reentrancy? * Useful Macros and Constants:: Convenient helpers. * Compatibility with older versions:: Compatibility issues. * Getting the Latest Version of GMP:: How to get the software.  File: gmp.info, Node: Nomenclature and Types, Next: Function Classes, Prev: GMP Basics, Up: GMP Basics Nomenclature and Types ====================== In this manual, "integer" usually means a multiple precision integer, as defined by the GMP library. The C data type for such integers is `mpz_t'. Here are some examples of how to declare such integers: mpz_t sum; struct foo { mpz_t x, y; }; mpz_t vec[20]; "Rational number" means a multiple precision fraction. The C data type for these fractions is `mpq_t'. For example: mpq_t quotient; "Floating point number" or "Float" for short, is an arbitrary precision mantissa with a limited precision exponent. The C data type for such objects is `mpf_t'. A "limb" means the part of a multi-precision number that fits in a single word. (We chose this word because a limb of the human body is analogous to a digit, only larger, and containing several digits.) Normally a limb contains 32 or 64 bits. The C data type for a limb is `mp_limb_t'.  File: gmp.info, Node: Function Classes, Next: GMP Variable Conventions, Prev: Nomenclature and Types, Up: GMP Basics Function Classes ================ There are six classes of functions in the GMP library: 1. Functions for signed integer arithmetic, with names beginning with `mpz_'. The associated type is `mpz_t'. There are about 100 functions in this class. 2. Functions for rational number arithmetic, with names beginning with `mpq_'. The associated type is `mpq_t'. There are about 20 functions in this class, but the functions in the previous class can be used for performing arithmetic on the numerator and denominator separately. 3. Functions for floating-point arithmetic, with names beginning with `mpf_'. The associated type is `mpf_t'. There are about 50 functions is this class. 4. Functions compatible with Berkeley GMP, such as `itom', `madd', and `mult'. The associated type is `MINT'. 5. Fast low-level functions that operate on natural numbers. These are used by the functions in the preceding groups, and you can also call them directly from very time-critical user programs. These functions' names begin with `mpn_'. There are about 30 (hard-to-use) functions in this class. The associated type is array of `mp_limb_t'. 6. Miscellaneous functions. Functions for setting up custom allocation and functions for generating random numbers.  File: gmp.info, Node: GMP Variable Conventions, Next: GMP and reentrancy, Prev: Function Classes, Up: GMP Basics GMP Variable Conventions ======================== As a general rule, all GMP functions expect output arguments before input arguments. This notation is based on an analogy with the assignment operator. (The BSD MP compatibility functions disobey this rule, having the output argument(s) last.) GMP allows you to use the same variable for both input and output in the same expression. For example, the main function for integer multiplication, `mpz_mul', can be used like this: `mpz_mul (x, x, x)'. This computes the square of X and puts the result back in X. Before you can assign to an GMP variable, you need to initialize it by calling one of the special initialization functions. When you're done with a variable, you need to clear it out, using one of the functions for that purpose. Which function to use depends on the type of variable. See the chapters on integer functions, rational number functions, and floating-point functions for details. A variable should only be initialized once, or at least cleared out between each initialization. After a variable has been initialized, it may be assigned to any number of times. For efficiency reasons, avoid initializing and clearing out an GMP variable in a loop. Instead, initialize it before entering the loop, and clear it out after the loop has exited Once you have initialized an GMP variable, you don't need to worry about space allocation for that variable. All functions in GMP automatically allocate additional space when a variable does not already have enough space. They do not, however, reduce the space when a smaller number is stored in the object. Most of the time, this policy is best, since it avoids frequent re-allocation.  File: gmp.info, Node: GMP and reentrancy, Next: Useful Macros and Constants, Prev: GMP Variable Conventions, Up: GMP Basics GMP and reentrancy ================== The GMP code is reentrant and thread-safe, with some exceptions: * The function `mpf_set_default_prec' saves the selected precision in a global variable. * The function `mp_set_memory_functions' uses several global variables for storing the selected memory allocation functions. * The memory allocation functions, `malloc' and friends, that GMP uses unless directed to use custom allocation, may not be reentrant. * The old random number functions (`mpz_random', etc) use an underlying random number generator from the C library, typically `mrand48' or `random'. These routines are not reentrant, since they rely on global state. (The newer random number functions that accept a `gmp_randstate_t' parameter are however reentrant.) If the memory allocation functions (`malloc' and friends, or whatever functions set by a call to `mp_set_memory_functions'), are not reentrant, GMP will not be reentrant either.  File: gmp.info, Node: Useful Macros and Constants, Next: Compatibility with older versions, Prev: GMP and reentrancy, Up: GMP Basics Useful Macros and Constants =========================== - Global Constant: const int mp_bits_per_limb The number of bits per limb. - Macro: __GNU_MP_VERSION - Macro: __GNU_MP_VERSION_MINOR - Macro: __GNU_MP_VERSION_PATCHLEVEL The major and minor GMP version, and patch level, respectively, as integers. For GMP i.j, these numbers will be i, j, and 0, respectively. For GMP i.j.k, these numbers will be i, j, and k, respectively.  File: gmp.info, Node: Compatibility with older versions, Next: Getting the Latest Version of GMP, Prev: Useful Macros and Constants, Up: GMP Basics Compatibility with older versions ================================= * Menu: * Compatibility with Version 1.x:: * Compatibility with Version 2.0.x::  File: gmp.info, Node: Compatibility with Version 1.x, Next: Compatibility with Version 2.0.x, Prev: Compatibility with older versions, Up: Compatibility with older versions Compatibility with Version 1.x ------------------------------ This version of GMP is upward compatible with previous versions of GMP, with a few exceptions. 1. Integer division functions round the result differently. The obsolete functions (`mpz_div', `mpz_divmod', `mpz_mdiv', `mpz_mdivmod', etc) now all use floor rounding (i.e., they round the quotient towards -infinity). There are a lot of functions for integer division, giving the user better control over the rounding. 2. The function `mpz_mod' now compute the true *mod* function. 3. The functions `mpz_powm' and `mpz_powm_ui' now use *mod* for reduction. 4. The assignment functions for rational numbers do no longer canonicalize their results. In the case a non-canonical result could arise from an assignment, the user need to insert an explicit call to `mpq_canonicalize'. This change was made for efficiency. 5. Output generated by `mpz_out_raw' in this release cannot be read by `mpz_inp_raw' in previous releases. This change was made for making the file format truly portable between machines with different word sizes. 6. Several `mpn' functions have changed. But they were intentionally undocumented in previous releases. 7. The functions `mpz_cmp_ui', `mpz_cmp_si', and `mpq_cmp_ui' are now implemented as macros, and thereby sometimes evaluate their arguments multiple times. 8. The functions `mpz_pow_ui' and `mpz_ui_pow_ui' now yield 1 for 0^0. (In version 1, they yielded 0.)  File: gmp.info, Node: Compatibility with Version 2.0.x, Prev: Compatibility with Version 1.x, Up: Compatibility with older versions Compatibility with Version 2.0.x -------------------------------- This version of GMP is upward compatible with version 2.0, 2.0.1, and 2.0.2 at the source level, with the exception of `mpn_gcd' which has had its source arguments swapped.  File: gmp.info, Node: Getting the Latest Version of GMP, Prev: Compatibility with older versions, Up: GMP Basics Getting the Latest Version of GMP ================================= The latest version of the GMP library is available by at `ftp://ftp.gnu.org/pub/gnu/gmp'. Many sites around the world mirror `ftp.gnu.org'; please use a mirror site near you.  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 that you find. Before you report a bug, you may want to check `http://www.swox.com/gmp/' for patches for this release. There are a few things you should think about when you put your bug report together. You have to send us a test case that makes it possible for us to reproduce the bug. Include instructions on how to run the test case. You also have to explain what is wrong; if you get a crash, or if the results printed are incorrect and in that case, in what way. It is not uncommon that an observed problem is actually due to a bug in the compiler used when building GMP; the GMP code tends to explore interesting corners in compilers. Therefore, please include compiler version information in your bug report. This can be extracted using `what `which cc`', or, if you're using gcc, `gcc -v'. Also, include the output from `uname -a'. If the bug is related to `configure', please include the file `config.log' in the bug report. If your bug report is good, we will do our best to help you to get a corrected version of the library; if the bug report is poor, we won't do anything about it (apart from chiding you to send better bug reports). Send your bug report to: . 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:: * Comparison Functions:: * Integer Logic and Bit Fiddling:: * I/O of Integers:: * Miscellaneous Integer Functions::  File: gmp.info, Node: Initializing Integers, Next: Assigning Integers, Up: Integer Functions Initialization and Assignment Functions ======================================= The functions for integer arithmetic assume that all integer objects are initialized. You do that by calling the function `mpz_init'. - Function: void mpz_init (mpz_t INTEGER) Initialize INTEGER with limb space and set the initial numeric value to 0. Each variable should normally only be initialized once, or at least cleared out (using `mpz_clear') between each initialization. Here is an example of using `mpz_init': { 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_clear (mpz_t INTEGER) Free the limb space occupied by INTEGER. Make sure to call this function for all `mpz_t' variables when you are done with them. - Function: void * _mpz_realloc (mpz_t INTEGER, mp_size_t NEW_ALLOC) Change the limb space allocation to NEW_ALLOC limbs. This function is not normally called from user code, but it can be used to give memory back to the heap, or to increase the space of a variable to avoid repeated automatic re-allocation. - Function: void mpz_array_init (mpz_t INTEGER_ARRAY[], size_t ARRAY_SIZE, mp_size_t FIXED_NUM_BITS) Allocate *fixed* limb space for all ARRAY_SIZE integers in INTEGER_ARRAY. The fixed allocation for each integer in the array is enough to store FIXED_NUM_BITS. If the fixed space will be insufficient for storing the result of a subsequent calculation, the result is unpredictable. This function is useful for decreasing the working set for some algorithms that use large integer arrays. There is no way to de-allocate the storage allocated by this function. Don't call `mpz_clear'!  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. - Function: int mpz_set_str (mpz_t ROP, char *STR, int BASE) Set the value of ROP from STR, a '\0'-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 up to the '\0' is a valid number in base BASE. Otherwise it returns -1. - 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: mp_limb_t mpz_getlimbn (mpz_t OP, mp_size_t N) Return limb #N from OP. This function allows for very efficient decomposition of a number in its limbs. The function `mpz_size' can be used to determine the useful range for N. - 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: 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, space for the result string is allocated using the default allocation function. If STR is not NULL, it should point to a block of storage enough large for the result. To find out the right amount of space to provide for STR, use `mpz_sizeinbase (OP, BASE) + 2'. The two extra bytes are for a possible minus sign, and for the terminating null character. A pointer to the result string is returned. This pointer will will either equal STR, or if that is NULL, will point to the allocated storage.  File: gmp.info, Node: Integer Arithmetic, Next: Comparison Functions, 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_ui (mpz_t ROP, mpz_t OP1, unsigned long int OP2) Set ROP to OP1 times OP2. - Function: void mpz_addmul_ui (mpz_t ROP, mpz_t OP1, unsigned long int OP2) Add OP1 times OP2 to ROP. - 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, OP2 steps. - 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. Division and mod functions -------------------------- Division is undefined if the divisor is zero, and passing a zero divisor to the divide or modulo functions, as well passing a zero mod argument to the `mpz_powm' and `mpz_powm_ui' functions, will make these functions intentionally divide by zero. This lets the user handle arithmetic exceptions in these functions in the same manner as other arithmetic exceptions. There are three main groups of division functions: * Functions that truncate the quotient towards 0. The names of these functions start with `mpz_tdiv'. The `t' in the name is short for `truncate'. * Functions that round the quotient towards -infinity). The names of these routines start with `mpz_fdiv'. The `f' in the name is short for `floor'. * Functions that round the quotient towards +infinity. The names of these routines start with `mpz_cdiv'. The `c' in the name is short for `ceil'. For each rounding mode, there are a couple of variants. Here `q' means that the quotient is computed, while `r' means that the remainder is computed. Functions that compute both the quotient and remainder have `qr' in the name. - Function: void mpz_tdiv_q (mpz_t Q, mpz_t N, mpz_t D) - Function: unsigned long int mpz_tdiv_q_ui (mpz_t Q, mpz_t N, unsigned long int D) Set Q to [N/D], truncated towards 0. The function `mpz_tdiv_q_ui' returns the absolute value of the true remainder. - Function: void mpz_tdiv_r (mpz_t R, mpz_t N, mpz_t D) - Function: unsigned long int mpz_tdiv_r_ui (mpz_t R, mpz_t N, unsigned long int D) Set R to (N - [N/D] * D), where the quotient is truncated towards 0. Unless R becomes zero, it will get the same sign as N. The function `mpz_tdiv_r_ui' returns the absolute value of the remainder. - Function: void mpz_tdiv_qr (mpz_t Q, mpz_t R, mpz_t N, mpz_t D) - Function: unsigned long int mpz_tdiv_qr_ui (mpz_t Q, mpz_t R, mpz_t N, unsigned long int D) Set Q to [N/D], truncated towards 0. Set R to (N - [N/D] * D). Unless R becomes zero, it will get the same sign as N. If Q and R are the same variable, the results are undefined. The function `mpz_tdiv_qr_ui' returns the absolute value of the remainder. - Function: unsigned long int mpz_tdiv_ui (mpz_t N, unsigned long int D) Like `mpz_tdiv_r_ui', but the remainder is not stored anywhere; its absolute value is just returned. - Function: void mpz_fdiv_q (mpz_t Q, mpz_t N, mpz_t D) - Function: unsigned long int mpz_fdiv_q_ui (mpz_t Q, mpz_t N, unsigned long int D) Set Q to N/D, rounded towards -infinity. The function `mpz_fdiv_q_ui' returns the remainder. - Function: void mpz_fdiv_r (mpz_t R, mpz_t N, mpz_t D) - Function: unsigned long int mpz_fdiv_r_ui (mpz_t R, mpz_t N, unsigned long int D) Set R to (N - N/D * D), where the quotient is rounded towards -infinity. Unless R becomes zero, it will get the same sign as D. The function `mpz_fdiv_r_ui' returns the remainder. - Function: void mpz_fdiv_qr (mpz_t Q, mpz_t R, mpz_t N, mpz_t D) - Function: unsigned long int mpz_fdiv_qr_ui (mpz_t Q, mpz_t R, mpz_t N, unsigned long int D) Set Q to N/D, rounded towards -infinity. Set R to (N - N/D * D). Unless R becomes zero, it will get the same sign as D. If Q and R are the same variable, the results are undefined. The function `mpz_fdiv_qr_ui' returns the remainder. - Function: unsigned long int mpz_fdiv_ui (mpz_t N, unsigned long int D) Like `mpz_fdiv_r_ui', but the remainder is not stored anywhere; it is just returned. - Function: void mpz_cdiv_q (mpz_t Q, mpz_t N, mpz_t D) - Function: unsigned long int mpz_cdiv_q_ui (mpz_t Q, mpz_t N, unsigned long int D) Set Q to N/D, rounded towards +infinity. The function `mpz_cdiv_q_ui' returns the negated remainder. - Function: void mpz_cdiv_r (mpz_t R, mpz_t N, mpz_t D) - Function: unsigned long int mpz_cdiv_r_ui (mpz_t R, mpz_t N, unsigned long int D) Set R to (N - N/D * D), where the quotient is rounded towards +infinity. Unless R becomes zero, it will get the opposite sign as D. The function `mpz_cdiv_r_ui' returns the negated remainder. - Function: void mpz_cdiv_qr (mpz_t Q, mpz_t R, mpz_t N, mpz_t D) - Function: unsigned long int mpz_cdiv_qr_ui (mpz_t Q, mpz_t R, mpz_t N, unsigned long int D) Set Q to N/D, rounded towards +infinity. Set R to (N - N/D * D). Unless R becomes zero, it will get the opposite sign as D. If Q and R are the same variable, the results are undefined. The function `mpz_cdiv_qr_ui' returns the negated remainder. - Function: unsigned long int mpz_cdiv_ui (mpz_t N, unsigned long int D) Like `mpz_tdiv_r_ui', but the remainder is not stored anywhere; its negated value is just returned. - 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. The function `mpz_mod_ui' returns the remainder. - Function: void mpz_divexact (mpz_t Q, mpz_t N, mpz_t D) Set Q to N/D. This function produces correct results only when it is known in advance that D divides N. Since mpz_divexact is much faster than any of the other routines that produce the quotient (*note References:: Jebelean), it is the best choice for instances in which exact division is known to occur, such as reducing a rational to lowest terms. - Function: void mpz_tdiv_q_2exp (mpz_t Q, mpz_t N, unsigned long int D) Set Q to N divided by 2 raised to D. The quotient is truncated towards 0. - Function: void mpz_tdiv_r_2exp (mpz_t R, mpz_t N, unsigned long int D) Divide N by (2 raised to D) and put the remainder in R. Unless it is zero, R will have the same sign as N. - Function: void mpz_fdiv_q_2exp (mpz_t Q, mpz_t N, unsigned long int D) Set Q to N divided by 2 raised to D, rounded towards -infinity. - Function: void mpz_fdiv_r_2exp (mpz_t R, mpz_t N, unsigned long int D) Divide N by (2 raised to D) and put the remainder in R. The sign of R will always be positive. This operation can also be defined as masking of the D least significant bits. 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) `mod' MOD. If EXP is negative, the result is undefined. - 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 of 0^0 yields 1. Root 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 OP-ROP1*ROP1, (i.e., 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 b. Return zero otherwise. - 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. Return zero otherwise. Number Theoretic Functions -------------------------- - Function: int mpz_probab_prime_p (mpz_t N, int REPS) If this function returns 0, N is definitely not prime. If it returns 1, then N is `probably' prime. If it returns 2, then N is surely prime. Reasonable values of reps vary from 5 to 10; a higher value lowers the probability for a non-prime to pass as a `probable' prime. The function uses Miller-Rabin's probabilistic test. - Function: int 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, but for for practical purposes it's adequate, since 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 either of 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 AS + BT = 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) Set ROP to the least common multiple of OP1 and OP2. - 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. Return non-zero if an inverse exist, zero otherwise. When the function returns zero, ROP is undefined. - Function: int mpz_jacobi (mpz_t OP1, mpz_t OP2) - Function: int mpz_legendre (mpz_t OP1, mpz_t OP2) Compute the Jacobi and Legendre symbols, respectively. - 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. - Function: void mpz_fib_ui (mpz_t ROP, unsigned long int N) Compute the Nth Fibonacci number and store the result in ROP.  File: gmp.info, Node: Comparison Functions, Next: Integer Logic and Bit Fiddling, Prev: Integer Arithmetic, Up: Integer Functions Comparison Functions ==================== - Function: int mpz_cmp (mpz_t OP1, mpz_t OP2) Compare OP1 and OP2. Return a positive value if OP1 > OP2, zero if OP1 = OP2, and a negative value if OP1 < OP2. - Macro: int mpz_cmp_ui (mpz_t OP1, unsigned long int OP2) - Macro: int mpz_cmp_si (mpz_t OP1, signed long int OP2) Compare OP1 and OP2. Return a positive value if OP1 > OP2, zero if OP1 = OP2, and a negative value if OP1 < OP2. These functions are actually implemented as macros. They evaluate their arguments multiple times. - Function: int mpz_cmpabs (mpz_t OP1, mpz_t 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 OP1 > OP2, zero if OP1 = OP2, and a negative value if OP1 < OP2. - 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 arguments multiple times.  File: gmp.info, Node: Integer Logic and Bit Fiddling, Next: I/O of Integers, Prev: Comparison Functions, Up: Integer Functions Logical and Bit Manipulation Functions ====================================== These functions behave as if two's complement arithmetic were used (although sign-magnitude is used by the actual implementation). - 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) For non-negative numbers, return the population count of OP. For negative numbers, return the largest possible value (MAX_ULONG). - Function: unsigned long int mpz_hamdist (mpz_t OP1, mpz_t OP2) If OP1 and OP2 are both non-negative, return the hamming distance between the two operands. Otherwise, return the largest possible value (MAX_ULONG). It is possible to extend this function to return a useful value when the operands are both negative, but the current implementation returns MAX_ULONG in this case. *Do not depend on this behavior, since it will change in a future release.* - Function: unsigned long int mpz_scan0 (mpz_t OP, unsigned long int STARTING_BIT) Scan OP, starting with bit STARTING_BIT, towards more significant bits, until the first clear bit is found. Return the index of the found bit. - Function: unsigned long int mpz_scan1 (mpz_t OP, unsigned long int STARTING_BIT) Scan OP, starting with bit STARTING_BIT, towards more significant bits, until the first set bit is found. Return the index of the found bit. - 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) Check bit BIT_INDEX in OP and return 0 or 1 accordingly.