gned int COUNT) Shift {SP, N} left by COUNT bits, and write the result to {RP, N}. The bits shifted out at the left are returned in the least significant COUNT bits of the return value (the rest of the return value is zero). COUNT must be in the range 1 to mp_bits_per_limb-1. The regions {SP, N} and {RP, N} may overlap, provided RP >= SP. This function is written in assembly for most CPUs. -- Function: mp_limb_t mpn_rshift (mp_limb_t *RP, const mp_limb_t *SP, mp_size_t N, unsigned int COUNT) Shift {SP, N} right by COUNT bits, and write the result to {RP, N}. The bits shifted out at the right are returned in the most significant COUNT bits of the return value (the rest of the return value is zero). COUNT must be in the range 1 to mp_bits_per_limb-1. The regions {SP, N} and {RP, N} may overlap, provided RP <= SP. This function is written in assembly for most CPUs. -- Function: int mpn_cmp (const mp_limb_t *S1P, const mp_limb_t *S2P, mp_size_t N) Compare {S1P, N} and {S2P, N} and return a positive value if S1 > S2, 0 if they are equal, or a negative value if S1 < S2. -- Function: mp_size_t mpn_gcd (mp_limb_t *RP, mp_limb_t *XP, mp_size_t XN, mp_limb_t *YP, mp_size_t YN) Set {RP, RETVAL} to the greatest common divisor of {XP, XN} and {YP, YN}. The result can be up to YN limbs, the return value is the actual number produced. Both source operands are destroyed. {XP, XN} must have at least as many bits as {YP, YN}. {YP, YN} must be odd. Both operands must have non-zero most significant limbs. No overlap is permitted between {XP, XN} and {YP, YN}. -- Function: mp_limb_t mpn_gcd_1 (const mp_limb_t *XP, mp_size_t XN, mp_limb_t YLIMB) Return the greatest common divisor of {XP, XN} and YLIMB. Both operands must be non-zero. -- Function: mp_size_t mpn_gcdext (mp_limb_t *GP, mp_limb_t *SP, mp_size_t *SN, mp_limb_t *XP, mp_size_t XN, mp_limb_t *YP, mp_size_t YN) Let U be defined by {XP, XN} and let V be defined by {YP, YN}. Compute the greatest common divisor G of U and V. Compute a cofactor S such that G = US + VT. The second cofactor T is not computed but can easily be obtained from (G - U*S) / V (the division will be exact). It is required that U >= V > 0. S satisfies S = 1 or abs(S) < V / (2 G). S = 0 if and only if V divides U (i.e., G = V). Store G at GP and let the return value define its limb count. Store S at SP and let |*SN| define its limb count. S can be negative; when this happens *SN will be negative. The areas at GP and SP should each have room for XN+1 limbs. The areas {XP, XN+1} and {YP, YN+1} are destroyed (i.e. the input operands plus an extra limb past the end of each). Compatibility note: GMP 4.3.0 and 4.3.1 defined S less strictly. Earlier as well as later GMP releases define S as described here. -- Function: mp_size_t mpn_sqrtrem (mp_limb_t *R1P, mp_limb_t *R2P, const mp_limb_t *SP, mp_size_t N) Compute the square root of {SP, N} and put the result at {R1P, ceil(N/2)} and the remainder at {R2P, RETVAL}. R2P needs space for N limbs, but the return value indicates how many are produced. The most significant limb of {SP, N} must be non-zero. The areas {R1P, ceil(N/2)} and {SP, N} must be completely separate. The areas {R2P, N} and {SP, N} must be either identical or completely separate. If the remainder is not wanted then R2P can be `NULL', and in this case the return value is zero or non-zero according to whether the remainder would have been zero or non-zero. A return value of zero indicates a perfect square. See also `mpz_perfect_square_p'. -- Function: mp_size_t mpn_get_str (unsigned char *STR, int BASE, mp_limb_t *S1P, mp_size_t S1N) Convert {S1P, S1N} to a raw unsigned char array at STR in base BASE, and return the number of characters produced. There may be leading zeros in the string. The string is not in ASCII; to convert it to printable format, add the ASCII codes for `0' or `A', depending on the base and range. BASE can vary from 2 to 256. The most significant limb of the input {S1P, S1N} must be non-zero. The input {S1P, S1N} is clobbered, except when BASE is a power of 2, in which case it's unchanged. The area at STR has to have space for the largest possible number represented by a S1N long limb array, plus one extra character. -- Function: mp_size_t mpn_set_str (mp_limb_t *RP, const unsigned char *STR, size_t STRSIZE, int BASE) Convert bytes {STR,STRSIZE} in the given BASE to limbs at RP. STR[0] is the most significant byte and STR[STRSIZE-1] is the least significant. Each byte should be a value in the range 0 to BASE-1, not an ASCII character. BASE can vary from 2 to 256. The return value is the number of limbs written to RP. If the most significant input byte is non-zero then the high limb at RP will be non-zero, and only that exact number of limbs will be required there. If the most significant input byte is zero then there may be high zero limbs written to RP and included in the return value. STRSIZE must be at least 1, and no overlap is permitted between {STR,STRSIZE} and the result at RP. -- Function: mp_bitcnt_t mpn_scan0 (const mp_limb_t *S1P, mp_bitcnt_t BIT) Scan S1P from bit position BIT for the next clear bit. It is required that there be a clear bit within the area at S1P at or beyond bit position BIT, so that the function has something to return. -- Function: mp_bitcnt_t mpn_scan1 (const mp_limb_t *S1P, mp_bitcnt_t BIT) Scan S1P from bit position BIT for the next set bit. It is required that there be a set bit within the area at S1P at or beyond bit position BIT, so that the function has something to return. -- Function: void mpn_random (mp_limb_t *R1P, mp_size_t R1N) -- Function: void mpn_random2 (mp_limb_t *R1P, mp_size_t R1N) Generate a random number of length R1N and store it at R1P. The most significant limb is always non-zero. `mpn_random' generates uniformly distributed limb data, `mpn_random2' generates long strings of zeros and ones in the binary representation. `mpn_random2' is intended for testing the correctness of the `mpn' routines. -- Function: mp_bitcnt_t mpn_popcount (const mp_limb_t *S1P, mp_size_t N) Count the number of set bits in {S1P, N}. -- Function: mp_bitcnt_t mpn_hamdist (const mp_limb_t *S1P, const mp_limb_t *S2P, mp_size_t N) Compute the hamming distance between {S1P, N} and {S2P, N}, which is the number of bit positions where the two operands have different bit values. -- Function: int mpn_perfect_square_p (const mp_limb_t *S1P, mp_size_t N) Return non-zero iff {S1P, N} is a perfect square. -- Function: void mpn_and_n (mp_limb_t *RP, const mp_limb_t *S1P, const mp_limb_t *S2P, mp_size_t N) Perform the bitwise logical and of {S1P, N} and {S2P, N}, and write the result to {RP, N}. -- Function: void mpn_ior_n (mp_limb_t *RP, const mp_limb_t *S1P, const mp_limb_t *S2P, mp_size_t N) Perform the bitwise logical inclusive or of {S1P, N} and {S2P, N}, and write the result to {RP, N}. -- Function: void mpn_xor_n (mp_limb_t *RP, const mp_limb_t *S1P, const mp_limb_t *S2P, mp_size_t N) Perform the bitwise logical exclusive or of {S1P, N} and {S2P, N}, and write the result to {RP, N}. -- Function: void mpn_andn_n (mp_limb_t *RP, const mp_limb_t *S1P, const mp_limb_t *S2P, mp_size_t N) Perform the bitwise logical and of {S1P, N} and the bitwise complement of {S2P, N}, and write the result to {RP, N}. -- Function: void mpn_iorn_n (mp_limb_t *RP, const mp_limb_t *S1P, const mp_limb_t *S2P, mp_size_t N) Perform the bitwise logical inclusive or of {S1P, N} and the bitwise complement of {S2P, N}, and write the result to {RP, N}. -- Function: void mpn_nand_n (mp_limb_t *RP, const mp_limb_t *S1P, const mp_limb_t *S2P, mp_size_t N) Perform the bitwise logical and of {S1P, N} and {S2P, N}, and write the bitwise complement of the result to {RP, N}. -- Function: void mpn_nior_n (mp_limb_t *RP, const mp_limb_t *S1P, const mp_limb_t *S2P, mp_size_t N) Perform the bitwise logical inclusive or of {S1P, N} and {S2P, N}, and write the bitwise complement of the result to {RP, N}. -- Function: void mpn_xnor_n (mp_limb_t *RP, const mp_limb_t *S1P, const mp_limb_t *S2P, mp_size_t N) Perform the bitwise logical exclusive or of {S1P, N} and {S2P, N}, and write the bitwise complement of the result to {RP, N}. -- Function: void mpn_com (mp_limb_t *RP, const mp_limb_t *SP, mp_size_t N) Perform the bitwise complement of {SP, N}, and write the result to {RP, N}. -- Function: void mpn_copyi (mp_limb_t *RP, const mp_limb_t *S1P, mp_size_t N) Copy from {S1P, N} to {RP, N}, increasingly. -- Function: void mpn_copyd (mp_limb_t *RP, const mp_limb_t *S1P, mp_size_t N) Copy from {S1P, N} to {RP, N}, decreasingly. -- Function: void mpn_zero (mp_limb_t *RP, mp_size_t N) Zero {RP, N}. 8.1 Nails ========= *Everything in this section is highly experimental and may disappear or be subject to incompatible changes in a future version of GMP.* Nails are an experimental feature whereby a few bits are left unused at the top of each `mp_limb_t'. This can significantly improve carry handling on some processors. All the `mpn' functions accepting limb data will expect the nail bits to be zero on entry, and will return data with the nails similarly all zero. This applies both to limb vectors and to single limb arguments. Nails can be enabled by configuring with `--enable-nails'. By default the number of bits will be chosen according to what suits the host processor, but a particular number can be selected with `--enable-nails=N'. At the mpn level, a nail build is neither source nor binary compatible with a non-nail build, strictly speaking. But programs acting on limbs only through the mpn functions are likely to work equally well with either build, and judicious use of the definitions below should make any program compatible with either build, at the source level. For the higher level routines, meaning `mpz' etc, a nail build should be fully source and binary compatible with a non-nail build. -- Macro: GMP_NAIL_BITS -- Macro: GMP_NUMB_BITS -- Macro: GMP_LIMB_BITS `GMP_NAIL_BITS' is the number of nail bits, or 0 when nails are not in use. `GMP_NUMB_BITS' is the number of data bits in a limb. `GMP_LIMB_BITS' is the total number of bits in an `mp_limb_t'. In all cases GMP_LIMB_BITS == GMP_NAIL_BITS + GMP_NUMB_BITS -- Macro: GMP_NAIL_MASK -- Macro: GMP_NUMB_MASK Bit masks for the nail and number parts of a limb. `GMP_NAIL_MASK' is 0 when nails are not in use. `GMP_NAIL_MASK' is not often needed, since the nail part can be obtained with `x >> GMP_NUMB_BITS', and that means one less large constant, which can help various RISC chips. -- Macro: GMP_NUMB_MAX The maximum value that can be stored in the number part of a limb. This is the same as `GMP_NUMB_MASK', but can be used for clarity when doing comparisons rather than bit-wise operations. The term "nails" comes from finger or toe nails, which are at the ends of a limb (arm or leg). "numb" is short for number, but is also how the developers felt after trying for a long time to come up with sensible names for these things. In the future (the distant future most likely) a non-zero nail might be permitted, giving non-unique representations for numbers in a limb vector. This would help vector processors since carries would only ever need to propagate one or two limbs.  File: gmp.info, Node: Random Number Functions, Next: Formatted Output, Prev: Low-level Functions, Up: Top 9 Random Number Functions ************************* Sequences of pseudo-random numbers in GMP are generated using a variable of type `gmp_randstate_t', which holds an algorithm selection and a current state. Such a variable must be initialized by a call to one of the `gmp_randinit' functions, and can be seeded with one of the `gmp_randseed' functions. The functions actually generating random numbers are described in *Note Integer Random Numbers::, and *Note Miscellaneous Float Functions::. The older style random number functions don't accept a `gmp_randstate_t' parameter but instead share a global variable of that type. They use a default algorithm and are currently not seeded (though perhaps that will change in the future). The new functions accepting a `gmp_randstate_t' are recommended for applications that care about randomness. * Menu: * Random State Initialization:: * Random State Seeding:: * Random State Miscellaneous::  File: gmp.info, Node: Random State Initialization, Next: Random State Seeding, Prev: Random Number Functions, Up: Random Number Functions 9.1 Random State Initialization =============================== -- Function: void gmp_randinit_default (gmp_randstate_t STATE) Initialize STATE with a default algorithm. This will be a compromise between speed and randomness, and is recommended for applications with no special requirements. Currently this is `gmp_randinit_mt'. -- Function: void gmp_randinit_mt (gmp_randstate_t STATE) Initialize STATE for a Mersenne Twister algorithm. This algorithm is fast and has good randomness properties. -- Function: void gmp_randinit_lc_2exp (gmp_randstate_t STATE, mpz_t A, unsigned long C, mp_bitcnt_t M2EXP) Initialize STATE with a linear congruential algorithm X = (A*X + C) mod 2^M2EXP. The low bits of X in this algorithm are not very random. The least significant bit will have a period no more than 2, and the second bit no more than 4, etc. For this reason only the high half of each X is actually used. When a random number of more than M2EXP/2 bits is to be generated, multiple iterations of the recurrence are used and the results concatenated. -- Function: int gmp_randinit_lc_2exp_size (gmp_randstate_t STATE, mp_bitcnt_t SIZE) Initialize STATE for a linear congruential algorithm as per `gmp_randinit_lc_2exp'. A, C and M2EXP are selected from a table, chosen so that SIZE bits (or more) of each X will be used, ie. M2EXP/2 >= SIZE. If successful the return value is non-zero. If SIZE is bigger than the table data provides then the return value is zero. The maximum SIZE currently supported is 128. -- Function: void gmp_randinit_set (gmp_randstate_t ROP, gmp_randstate_t OP) Initialize ROP with a copy of the algorithm and state from OP. -- Function: void gmp_randinit (gmp_randstate_t STATE, gmp_randalg_t ALG, ...) *This function is obsolete.* Initialize STATE with an algorithm selected by ALG. The only choice is `GMP_RAND_ALG_LC', which is `gmp_randinit_lc_2exp_size' described above. A third parameter of type `unsigned long' is required, this is the SIZE for that function. `GMP_RAND_ALG_DEFAULT' or 0 are the same as `GMP_RAND_ALG_LC'. `gmp_randinit' sets bits in the global variable `gmp_errno' to indicate an error. `GMP_ERROR_UNSUPPORTED_ARGUMENT' if ALG is unsupported, or `GMP_ERROR_INVALID_ARGUMENT' if the SIZE parameter is too big. It may be noted this error reporting is not thread safe (a good reason to use `gmp_randinit_lc_2exp_size' instead). -- Function: void gmp_randclear (gmp_randstate_t STATE) Free all memory occupied by STATE.  File: gmp.info, Node: Random State Seeding, Next: Random State Miscellaneous, Prev: Random State Initialization, Up: Random Number Functions 9.2 Random State Seeding ======================== -- Function: void gmp_randseed (gmp_randstate_t STATE, mpz_t SEED) -- Function: void gmp_randseed_ui (gmp_randstate_t STATE, unsigned long int SEED) Set an initial seed value into STATE. The size of a seed determines how many different sequences of random numbers that it's possible to generate. The "quality" of the seed is the randomness of a given seed compared to the previous seed used, and this affects the randomness of separate number sequences. The method for choosing a seed is critical if the generated numbers are to be used for important applications, such as generating cryptographic keys. Traditionally the system time has been used to seed, but care needs to be taken with this. If an application seeds often and the resolution of the system clock is low, then the same sequence of numbers might be repeated. Also, the system time is quite easy to guess, so if unpredictability is required then it should definitely not be the only source for the seed value. On some systems there's a special device `/dev/random' which provides random data better suited for use as a seed.  File: gmp.info, Node: Random State Miscellaneous, Prev: Random State Seeding, Up: Random Number Functions 9.3 Random State Miscellaneous ============================== -- Function: unsigned long gmp_urandomb_ui (gmp_randstate_t STATE, unsigned long N) Return a uniformly distributed random number of N bits, ie. in the range 0 to 2^N-1 inclusive. N must be less than or equal to the number of bits in an `unsigned long'. -- Function: unsigned long gmp_urandomm_ui (gmp_randstate_t STATE, unsigned long N) Return a uniformly distributed random number in the range 0 to N-1, inclusive.  File: gmp.info, Node: Formatted Output, Next: Formatted Input, Prev: Random Number Functions, Up: Top 10 Formatted Output ******************* * Menu: * Formatted Output Strings:: * Formatted Output Functions:: * C++ Formatted Output::  File: gmp.info, Node: Formatted Output Strings, Next: Formatted Output Functions, Prev: Formatted Output, Up: Formatted Output 10.1 Format Strings =================== `gmp_printf' and friends accept format strings similar to the standard C `printf' (*note Formatted Output: (libc)Formatted Output.). A format specification is of the form % [flags] [width] [.[precision]] [type] conv GMP adds types `Z', `Q' and `F' for `mpz_t', `mpq_t' and `mpf_t' respectively, `M' for `mp_limb_t', and `N' for an `mp_limb_t' array. `Z', `Q', `M' and `N' behave like integers. `Q' will print a `/' and a denominator, if needed. `F' behaves like a float. For example, mpz_t z; gmp_printf ("%s is an mpz %Zd\n", "here", z); mpq_t q; gmp_printf ("a hex rational: %#40Qx\n", q); mpf_t f; int n; gmp_printf ("fixed point mpf %.*Ff with %d digits\n", n, f, n); mp_limb_t l; gmp_printf ("limb %Mu\n", l); const mp_limb_t *ptr; mp_size_t size; gmp_printf ("limb array %Nx\n", ptr, size); For `N' the limbs are expected least significant first, as per the `mpn' functions (*note Low-level Functions::). A negative size can be given to print the value as a negative. All the standard C `printf' types behave the same as the C library `printf', and can be freely intermixed with the GMP extensions. In the current implementation the standard parts of the format string are simply handed to `printf' and only the GMP extensions handled directly. The flags accepted are as follows. GLIBC style ' is only for the standard C types (not the GMP types), and only if the C library supports it. 0 pad with zeros (rather than spaces) # show the base with `0x', `0X' or `0' + always show a sign (space) show a space or a `-' sign ' group digits, GLIBC style (not GMP types) The optional width and precision can be given as a number within the format string, or as a `*' to take an extra parameter of type `int', the same as the standard `printf'. The standard types accepted are as follows. `h' and `l' are portable, the rest will depend on the compiler (or include files) for the type and the C library for the output. h short hh char j intmax_t or uintmax_t l long or wchar_t ll long long L long double q quad_t or u_quad_t t ptrdiff_t z size_t The GMP types are F mpf_t, float conversions Q mpq_t, integer conversions M mp_limb_t, integer conversions N mp_limb_t array, integer conversions Z mpz_t, integer conversions The conversions accepted are as follows. `a' and `A' are always supported for `mpf_t' but depend on the C library for standard C float types. `m' and `p' depend on the C library. a A hex floats, C99 style c character d decimal integer e E scientific format float f fixed point float i same as d g G fixed or scientific float m `strerror' string, GLIBC style n store characters written so far o octal integer p pointer s string u unsigned integer x X hex integer `o', `x' and `X' are unsigned for the standard C types, but for types `Z', `Q' and `N' they are signed. `u' is not meaningful for `Z', `Q' and `N'. `M' is a proxy for the C library `l' or `L', according to the size of `mp_limb_t'. Unsigned conversions will be usual, but a signed conversion can be used and will interpret the value as a twos complement negative. `n' can be used with any type, even the GMP types. Other types or conversions that might be accepted by the C library `printf' cannot be used through `gmp_printf', this includes for instance extensions registered with GLIBC `register_printf_function'. Also currently there's no support for POSIX `$' style numbered arguments (perhaps this will be added in the future). The precision field has it's usual meaning for integer `Z' and float `F' types, but is currently undefined for `Q' and should not be used with that. `mpf_t' conversions only ever generate as many digits as can be accurately represented by the operand, the same as `mpf_get_str' does. Zeros will be used if necessary to pad to the requested precision. This happens even for an `f' conversion of an `mpf_t' which is an integer, for instance 2^1024 in an `mpf_t' of 128 bits precision will only produce about 40 digits, then pad with zeros to the decimal point. An empty precision field like `%.Fe' or `%.Ff' can be used to specifically request just the significant digits. The decimal point character (or string) is taken from the current locale settings on systems which provide `localeconv' (*note Locales and Internationalization: (libc)Locales.). The C library will normally do the same for standard float output. The format string is only interpreted as plain `char's, multibyte characters are not recognised. Perhaps this will change in the future.  File: gmp.info, Node: Formatted Output Functions, Next: C++ Formatted Output, Prev: Formatted Output Strings, Up: Formatted Output 10.2 Functions ============== Each of the following functions is similar to the corresponding C library function. The basic `printf' forms take a variable argument list. The `vprintf' forms take an argument pointer, see *Note Variadic Functions: (libc)Variadic Functions, or `man 3 va_start'. It should be emphasised that if a format string is invalid, or the arguments don't match what the format specifies, then the behaviour of any of these functions will be unpredictable. GCC format string checking is not available, since it doesn't recognise the GMP extensions. The file based functions `gmp_printf' and `gmp_fprintf' will return -1 to indicate a write error. Output is not "atomic", so partial output may be produced if a write error occurs. All the functions can return -1 if the C library `printf' variant in use returns -1, but this shouldn't normally occur. -- Function: int gmp_printf (const char *FMT, ...) -- Function: int gmp_vprintf (const char *FMT, va_list AP) Print to the standard output `stdout'. Return the number of characters written, or -1 if an error occurred. -- Function: int gmp_fprintf (FILE *FP, const char *FMT, ...) -- Function: int gmp_vfprintf (FILE *FP, const char *FMT, va_list AP) Print to the stream FP. Return the number of characters written, or -1 if an error occurred. -- Function: int gmp_sprintf (char *BUF, const char *FMT, ...) -- Function: int gmp_vsprintf (char *BUF, const char *FMT, va_list AP) Form a null-terminated string in BUF. Return the number of characters written, excluding the terminating null. No overlap is permitted between the space at BUF and the string FMT. These functions are not recommended, since there's no protection against exceeding the space available at BUF. -- Function: int gmp_snprintf (char *BUF, size_t SIZE, const char *FMT, ...) -- Function: int gmp_vsnprintf (char *BUF, size_t SIZE, const char *FMT, va_list AP) Form a null-terminated string in BUF. No more than SIZE bytes will be written. To get the full output, SIZE must be enough for the string and null-terminator. The return value is the total number of characters which ought to have been produced, excluding the terminating null. If RETVAL >= SIZE then the actual output has been truncated to the first SIZE-1 characters, and a null appended. No overlap is permitted between the region {BUF,SIZE} and the FMT string. Notice the return value is in ISO C99 `snprintf' style. This is so even if the C library `vsnprintf' is the older GLIBC 2.0.x style. -- Function: int gmp_asprintf (char **PP, const char *FMT, ...) -- Function: int gmp_vasprintf (char **PP, const char *FMT, va_list AP) Form a null-terminated string in a block of memory obtained from the current memory allocation function (*note Custom Allocation::). The block will be the size of the string and null-terminator. The address of the block in stored to *PP. The return value is the number of characters produced, excluding the null-terminator. Unlike the C library `asprintf', `gmp_asprintf' doesn't return -1 if there's no more memory available, it lets the current allocation function handle that. -- Function: int gmp_obstack_printf (struct obstack *OB, const char *FMT, ...) -- Function: int gmp_obstack_vprintf (struct obstack *OB, const char *FMT, va_list AP) Append to the current object in OB. The return value is the number of characters written. A null-terminator is not written. FMT cannot be within the current object in OB, since that object might move as it grows. These functions are available only when the C library provides the obstack feature, which probably means only on GNU systems, see *Note Obstacks: (libc)Obstacks.  File: gmp.info, Node: C++ Formatted Output, Prev: Formatted Output Functions, Up: Formatted Output 10.3 C++ Formatted Output ========================= The following functions are provided in `libgmpxx' (*note Headers and Libraries::), which is built if C++ support is enabled (*note Build Options::). Prototypes are available from `'. -- Function: ostream& operator<< (ostream& STREAM, mpz_t OP) Print OP to STREAM, using its `ios' formatting settings. `ios::width' is reset to 0 after output, the same as the standard `ostream operator<<' routines do. In hex or octal, OP is printed as a signed number, the same as for decimal. This is unlike the standard `operator<<' routines on `int' etc, which instead give twos complement. -- Function: ostream& operator<< (ostream& STREAM, mpq_t OP) Print OP to STREAM, using its `ios' formatting settings. `ios::width' is reset to 0 after output, the same as the standard `ostream operator<<' routines do. Output will be a fraction like `5/9', or if the denominator is 1 then just a plain integer like `123'. In hex or octal, OP is printed as a signed value, the same as for decimal. If `ios::showbase' is set then a base indicator is shown on both the numerator and denominator (if the denominator is required). -- Function: ostream& operator<< (ostream& STREAM, mpf_t OP) Print OP to STREAM, using its `ios' formatting settings. `ios::width' is reset to 0 after output, the same as the standard `ostream operator<<' routines do. The decimal point follows the standard library float `operator<<', which on recent systems means the `std::locale' imbued on STREAM. Hex and octal are supported, unlike the standard `operator<<' on `double'. The mantissa will be in hex or octal, the exponent will be in decimal. For hex the exponent delimiter is an `@'. This is as per `mpf_out_str'. `ios::showbase' is supported, and will put a base on the mantissa, for example hex `0x1.8' or `0x0.8', or octal `01.4' or `00.4'. This last form is slightly strange, but at least differentiates itself from decimal. These operators mean that GMP types can be printed in the usual C++ way, for example, mpz_t z; int n; ... cout << "iteration " << n << " value " << z << "\n"; But note that `ostream' output (and `istream' input, *note C++ Formatted Input::) is the only overloading available for the GMP types and that for instance using `+' with an `mpz_t' will have unpredictable results. For classes with overloading, see *Note C++ Class Interface::.  File: gmp.info, Node: Formatted Input, Next: C++ Class Interface, Prev: Formatted Output, Up: Top 11 Formatted Input ****************** * Menu: * Formatted Input Strings:: * Formatted Input Functions:: * C++ Formatted Input::  File: gmp.info, Node: Formatted Input Strings, Next: Formatted Input Functions, Prev: Formatted Input, Up: Formatted Input 11.1 Formatted Input Strings ============================ `gmp_scanf' and friends accept format strings similar to the standard C `scanf' (*note Formatted Input: (libc)Formatted Input.). A format specification is of the form % [flags] [width] [type] conv GMP adds types `Z', `Q' and `F' for `mpz_t', `mpq_t' and `mpf_t' respectively. `Z' and `Q' behave like integers. `Q' will read a `/' and a denominator, if present. `F' behaves like a float. GMP variables don't require an `&' when passed to `gmp_scanf', since they're already "call-by-reference". For example, /* to read say "a(5) = 1234" */ int n; mpz_t z; gmp_scanf ("a(%d) = %Zd\n", &n, z); mpq_t q1, q2; gmp_sscanf ("0377 + 0x10/0x11", "%Qi + %Qi", q1, q2); /* to read say "topleft (1.55,-2.66)" */ mpf_t x, y; char buf[32]; gmp_scanf ("%31s (%Ff,%Ff)", buf, x, y); All the standard C `scanf' types behave the same as in the C library `scanf', and can be freely intermixed with the GMP extensions. In the current implementation the standard parts of the format string are simply handed to `scanf' and only the GMP extensions handled directly. The flags accepted are as follows. `a' and `'' will depend on support from the C library, and `'' cannot be used with GMP types. * read but don't store a allocate a buffer (string conversions) ' grouped digits, GLIBC style (not GMP types) The standard types accepted are as follows. `h' and `l' are portable, the rest will depend on the compiler (or include files) for the type and the C library for the input. h short hh char j intmax_t or uintmax_t l long int, double or wchar_t ll long long L long double q quad_t or u_quad_t t ptrdiff_t z size_t The GMP types are F mpf_t, float conversions Q mpq_t, integer conversions Z mpz_t, integer conversions The conversions accepted are as follows. `p' and `[' will depend on support from the C library, the rest are standard. c character or characters d decimal integer e E f g G float i integer with base indicator n characters read so far o octal integer p pointer s string of non-whitespace characters u decimal integer x X hex integer [ string of characters in a set `e', `E', `f', `g' and `G' are identical, they all read either fixed point or scientific format, and either upper or lower case `e' for the exponent in scientific format. C99 style hex float format (`printf %a', *note Formatted Output Strings::) is always accepted for `mpf_t', but for the standard float types it will depend on the C library. `x' and `X' are identical, both accept both upper and lower case hexadecimal. `o', `u', `x' and `X' all read positive or negative values. For the standard C types these are described as "unsigned" conversions, but that merely affects certain overflow handling, negatives are still allowed (per `strtoul', *note Parsing of Integers: (libc)Parsing of Integers.). For GMP types there are no overflows, so `d' and `u' are identical. `Q' type reads the numerator and (optional) denominator as given. If the value might not be in canonical form then `mpq_canonicalize' must be called before using it in any calculations (*note Rational Number Functions::). `Qi' will read a base specification separately for the numerator and denominator. For example `0x10/11' would be 16/11, whereas `0x10/0x11' would be 16/17. `n' can be used with any of the types above, even the GMP types. `*' to suppress assignment is allowed, though in that case it would do nothing at all. Other conversions or types that might be accepted by the C library `scanf' cannot be used through `gmp_scanf'. Whitespace is read and discarded before a field, except for `c' and `[' conversions. For float conversions, the decimal point character (or string) expected is taken from the current locale settings on systems which provide `localeconv' (*note Locales and Internationalization: (libc)Locales.). The C library will normally do the same for standard float input. The format string is only interpreted as plain `char's, multibyte characters are not recognised. Perhaps this will change in the future.  File: gmp.info, Node: Formatted Input Functions, Next: C++ Formatted Input, Prev: Formatted Input Strings, Up: Formatted Input 11.2 Formatted Input Functions ============================== Each of the following functions is similar to the corresponding C library function. The plain `scanf' forms take a variable argument list. The `vscanf' forms take an argument pointer, see *Note Variadic Functions: (libc)Variadic Functions, or `man 3 va_start'. It should be emphasised that if a format string is invalid, or the arguments don't match what the format specifies, then the behaviour of any of these functions will be unpredictable. GCC format string checking is not available, since it doesn't recognise the GMP extensions. No overlap is permitted between the FMT string and any of the results produced. -- Function: int gmp_scanf (const char *FMT, ...) -- Function: int gmp_vscanf (const char *FMT, va_list AP) Read from the standard input `stdin'. -- Function: int gmp_fscanf (FILE *FP, const char *FMT, ...) -- Function: int gmp_vfscanf (FILE *FP, const char *FMT, va_list AP) Read from the stream FP. -- Function: int gmp_sscanf (const char *S, const char *FMT, ...) -- Function: int gmp_vsscanf (const char *S, const char *FMT, va_list AP) Read from a null-terminated string S. The return value from each of these functions is the same as the standard C99 `scanf', namely the number of fields successfully parsed and stored. `%n' fields and fields read but suppressed by `*' don't count towards the return value. If end of input (or a file error) is reached before a character for a field or a literal, and if no previous non-suppressed fields have matched, then the return value is `EOF' instead of 0. A whitespace character in the format string is only an optional match and doesn't induce an `EOF' in this fashion. Leading whitespace read and discarded for a field don't count as characters for that field. For the GMP types, input parsing follows C99 rules, namely one character of lookahead is used and characters are read while they continue to meet the format requirements. If this doesn't provide a complete number then the function terminates, with that field not stored nor counted towards the return value. For instance with `mpf_t' an input `1.23e-XYZ' would be read up to the `X' and that character pushed back since it's not a digit. The string `1.23e-' would then be considered invalid since an `e' must be followed by at least one digit. For the standard C types, in the current implementation GMP calls the C library `scanf' functions, which might have looser rules about what constitutes a valid input. Note that `gmp_sscanf' is the same as `gmp_fscanf' and only does one character of lookahead when parsing. Although clearly it could look at its entire input, it is deliberately made identical to `gmp_fscanf', the same way C99 `sscanf' is the same as `fscanf'.  File: gmp.info, Node: C++ Formatted Input, Prev: Formatted Input Functions, Up: Formatted Input 11.3 C++ Formatted Input ======================== The following functions are provided in `libgmpxx' (*note Headers and Libraries::), which is built only if C++ support is enabled (*note Build Options::). Prototypes are available from `'. -- Function: istream& operator>> (istream& STREAM, mpz_t ROP) Read ROP from STREAM, using its `ios' formatting settings. -- Function: istream& operator>> (istream& STREAM, mpq_t ROP) An integer like `123' will be read, or a fraction like `5/9'. No whitespace is allowed around the `/'. If the fraction is not in canonical form then `mpq_canonicalize' must be called (*note Rational Number Functions::) before operating on it. As per integer input, an `0' or `0x' base indicator is read when none of `ios::dec', `ios::oct' or `ios::hex' are set. This is done separately for numerator and denominator, so that for instance `0x10/11' is 16/11 and `0x10/0x11' is 16/17. -- Function: istream& operator>> (istream& STREAM, mpf_t ROP) Read ROP from STREAM, using its `ios' formatting settings. Hex or octal floats are not supported, but might be in the future, or perhaps it's best to accept only what the standard float `operator>>' does. Note that digit grouping specified by the `istream' locale is currently not accepted. Perhaps this will change in the future. These operators mean that GMP types can be read in the usual C++ way, for example, mpz_t z; ... cin >> z; But note that `istream' input (and `ostream' output, *note C++ Formatted Output::) is the only overloading available for the GMP types and that for instance using `+' with an `mpz_t' will have unpredictable results. For classes with overloading, see *Note C++ Class Interface::.  File: gmp.info, Node: C++ Class Interface, Next: BSD Compatible Functions, Prev: Formatted Input, Up: Top 12 C++ Class Interface ********************** This chapter describes the C++ class based interface to GMP. All GMP C language types and functions can be used in C++ programs, since `gmp.h' has `extern "C"' qualifiers, but the class interface offers overloaded functions and operators which may be more convenient. Due to the implementation of this interface, a reasonably recent C++ compiler is required, one supporting namespaces, partial specialization of templates and member templates. For GCC this means version 2.91 or later. *Everything described in this chapter is to be considered preliminary and might be subject to incompatible changes if some unforeseen difficulty reveals itself.* * Menu: * C++ Interface General:: * C++ Interface Integers:: * C++ Interface Rationals:: * C++ Interface Floats:: * C++ Interface Random Numbers:: * C++ Interface Limitations::  File: gmp.info, Node: C++ Interface General, Next: C++ Interface Integers, Prev: C++ Class Interface, Up: C++ Class Interface 12.1 C++ Interface General ========================== All the C++ classes and functions are available with #include Programs should be linked with the `libgmpxx' and `libgmp' libraries. For example, g++ mycxxprog.cc -lgmpxx -lgmp The classes defined are -- Class: mpz_class -- Class: mpq_class -- Class: mpf_class The standard operators and various standard functions are overloaded to allow arithmetic with these classes. For example, int main (void) { mpz_class a, b, c; a = 1234; b = "-5678"; c = a+b; cout << "sum is " << c << "\n"; cout << "absolute value is " << abs(c) << "\n"; return 0; } An important feature of the implementation is that an expression like `a=b+c' results in a single call to the corresponding `mpz_add', without using a temporary for the `b+c' part. Expressions which by their nature imply intermediate values, like `a=b*c+d*e', still use temporaries though. The classes can be freely intermixed in expressions, as can the classes and the standard types `long', `unsigned long' and `double'. Smaller types like `int' or `float' can also be intermixed, since C++ will promote them. Note that `bool' is not accepted directly, but must be explicitly cast to an `int' first. This is because C++ will automatically convert any pointer to a `bool', so if GMP accepted `bool' it would make all sorts of invalid class and pointer combinations compile but almost certainly not do anything sensible. Conversions back from the classes to standard C++ types aren't done automatically, instead member functions like `get_si' are provided (see the following sections for details). Also there are no automatic conversions from the classes to the corresponding GMP C types, instead a reference to the underlying C object can be obtained with the following functions, -- Function: mpz_t mpz_class::get_mpz_t () -- Function: mpq_t mpq_class::get_mpq_t () -- Function: mpf_t mpf_class::get_mpf_t () These can be used to call a C function which doesn't have a C++ class interface. For example to set `a' to the GCD of `b' and `c', mpz_class a, b, c; ... mpz_gcd (a.get_mpz_t(), b.get_mpz_t(), c.get_mpz_t()); In the other direction, a class can be initialized from the corresponding GMP C type, or assigned to if an explicit constructor is used. In both cases this makes a copy of the value, it doesn't create any sort of association. For example, mpz_t z; // ... init and calculate z ... mpz_class x(z); mpz_class y; y = mpz_class (z); There are no namespace setups in `gmpxx.h', all types and functions are simply put into the global namespace. This is what `gmp.h' has done in the past, and continues to do for compatibility. The extras provided by `gmpxx.h' follow GMP naming conventions and are unlikely to clash with anything.  File: gmp.info, Node: C++ Interface Integers, Next: C++ Interface Rationals, Prev: C++ Interface General, Up: C++ Class Interface 12.2 C++ Interface Integers =========================== -- Function: void mpz_class::mpz_class (type N) Construct an `mpz_class'. All the standard C++ types may be used, except `long long' and `long double', and all the GMP C++ classes can be used. Any necessary conversion follows the corresponding C function, for example `double' follows `mpz_set_d' (*note Assigning Integers::). -- Function: void mpz_class::mpz_class (mpz_t Z) Construct an `mpz_class' from an `mpz_t'. The value in Z is copied into the new `mpz_class', there won't be any permanent association between it and Z. -- Function: void mpz_class::mpz_class (const char *S) -- Function: void mpz_class::mpz_class (const char *S, int BASE = 0) -- Function: void mpz_class::mpz_class (const string& S) -- Function: void mpz_class::mpz_class (const string& S, int BASE = 0) Construct an `mpz_class' converted from a string using `mpz_set_str' (*note Assigning Integers::). If the string is not a valid integer, an `std::invalid_argument' exception is thrown. The same applies to `operator='. -- Function: mpz_class operator/ (mpz_class A, mpz_class D) -- Function: mpz_class operator% (mpz_class A, mpz_class D) Divisions involving `mpz_class' round towards zero, as per the `mpz_tdiv_q' and `mpz_tdiv_r' functions (*note Integer Division::). This is the same as the C99 `/' and `%' operators. The `mpz_fdiv...' or `mpz_cdiv...' functions can always be called directly if desired. For example, mpz_class q, a, d; ... mpz_fdiv_q (q.get_mpz_t(), a.get_mpz_t(), d.get_mpz_t()); -- Function: mpz_class abs (mpz_class OP1) -- Function: int cmp (mpz_class OP1, type OP2) -- Function: int cmp (type OP1, mpz_class OP2) -- Function: bool mpz_class::fits_sint_p (void) -- Function: bool mpz_class::fits_slong_p (void) -- Function: bool mpz_class::fits_sshort_p (void) -- Function: bool mpz_class::fits_uint_p (void) -- Function: bool mpz_class::fits_ulong_p (void) -- Function: bool mpz_class::fits_ushort_p (void) -- Function: double mpz_class::get_d (void) -- Function: long mpz_class::get_si (void) -- Function: string mpz_class::get_str (int BASE = 10) -- Function: unsigned long mpz_class::get_ui (void) -- Function: int mpz_class::set_str (const char *STR, int BASE) -- Function: int mpz_class::set_str (const string& STR, int BASE) -- Function: int sgn (mpz_class OP) -- Function: mpz_class sqrt (mpz_class OP) These functions provide a C++ class interface to the corresponding GMP C routines. `cmp' can be used with any of the classes or the standard C++ types, except `long long' and `long double'. Overloaded operators for combinations of `mpz_class' and `double' are provided for completeness, but it should be noted that if the given `double' is not an integer then the way any rounding is done is currently unspecified. The rounding might take place at the start, in the middle, or at the end of the operation, and it might change in the future. Conversions between `mpz_class' and `double', however, are defined to follow the corresponding C functions `mpz_get_d' and `mpz_set_d'. And comparisons are always made exactly, as per `mpz_cmp_d'.  File: gmp.info, Node: C++ Interface Rationals, Next: C++ Interface Floats, Prev: C++ Interface Integers, Up: C++ Class Interface 12.3 C++ Interface Rationals ============================ In all the following constructors, if a fraction is given then it should be in canonical form, or if not then `mpq_class::canonicalize' called. -- Function: void mpq_class::mpq_class (type OP) -- Function: void mpq_class::mpq_class (integer NUM, integer DEN) Construct an `mpq_class'. The initial value can be a single value of any type, or a pair of integers (`mpz_class' or standard C++ integer types) representing a fraction, except that `long long' and `long double' are not supported. For example, mpq_class q (99); mpq_class q (1.75); mpq_class q (1, 3); -- Function: void mpq_class::mpq_class (mpq_t Q) Construct an `mpq_class' from an `mpq_t'. The value in Q is copied into the new `mpq_class', there won't be any permanent association between it and Q. -- Function: void mpq_class::mpq_class (const char *S) -- Function: void mpq_class::mpq_class (const char *S, int BASE = 0) -- Function: void mpq_class::mpq_class (const string& S) -- Function: void mpq_class::mpq_class (const string& S, int BASE = 0) Construct an `mpq_class' converted from a string using `mpq_set_str' (*note Initializing Rationals::). If the string is not a valid rational, an `std::invalid_argument' exception is thrown. The same applies to `operator='. -- Function: void mpq_class::canonicalize () Put an `mpq_class' into canonical form, as per *Note Rational Number Functions::. All arithmetic operators require their operands in canonical form, and will return results in canonical form. -- Function: mpq_class abs (mpq_class OP) -- Function: int cmp (mpq_class OP1, type OP2) -- Function: int cmp (type OP1, mpq_class OP2) -- Function: double mpq_class::get_d (void) -- Function: string mpq_class::get_str (int BASE = 10) -- Function: int mpq_class::set_str (const char *STR, int BASE) -- Function: int mpq_class::set_str (const string& STR, int BASE) -- Function: int sgn (mpq_class OP) These functions provide a C++ class interface to the corresponding GMP C routines. `cmp' can be used with any of the classes or the standard C++ types, except `long long' and `long double'. -- Function: mpz_class& mpq_class::get_num () -- Function: mpz_class& mpq_class::get_den () Get a reference to an `mpz_class' which is the numerator or denominator of an `mpq_class'. This can be used both for read and write access. If the object returned is modified, it modifies the original `mpq_class'. If direct manipulation might produce a non-canonical value, then `mpq_class::canonicalize' must be called before further operations. -- Function: mpz_t mpq_class::get_num_mpz_t () -- Function: mpz_t mpq_class::get_den_mpz_t () Get a reference to the underlying `mpz_t' numerator or denominator of an `mpq_class'. This can be passed to C functions expecting an `mpz_t'. Any modifications made to the `mpz_t' will modify the original `mpq_class'. If direct manipulation might produce a non-canonical value, then `mpq_class::canonicalize' must be called before further operations. -- Function: istream& operator>> (istream& STREAM, mpq_class& ROP); Read ROP from STREAM, using its `ios' formatting settings, the same as `mpq_t operator>>' (*note C++ Formatted Input::). If the ROP read might not be in canonical form then `mpq_class::canonicalize' must be called.  File: gmp.info, Node: C++ Interface Floats, Next: C++ Interface Random Numbers, Prev: C++ Interface Rationals, Up: C++ Class Interface 12.4 C++ Interface Floats ========================= When an expression requires the use of temporary intermediate `mpf_class' values, like `f=g*h+x*y', those temporaries will have the same precision as the destination `f'. Explicit constructors can be used if this doesn't suit. -- Function: mpf_class::mpf_class (type OP) -- Function: mpf_class::mpf_class (type OP, unsigned long PREC) Construct an `mpf_class'. Any standard C++ type can be used, except `long long' and `long double', and any of the GMP C++ classes can be used. If PREC is given, the initial precision is that value, in bits. If PREC is not given, then the initial precision is determined by the type of OP given. An `mpz_class', `mpq_class', or C++ builtin type will give the default `mpf' precision (*note Initializing Floats::). An `mpf_class' or expression will give the precision of that value. The precision of a binary expression is the higher of the two operands. mpf_class f(1.5); // default precision mpf_class f(1.5, 500); // 500 bits (at least) mpf_class f(x); // precision of x mpf_class f(abs(x)); // precision of x mpf_class f(-g, 1000); // 1000 bits (at least) mpf_class f(x+y); // greater of precisions of x and y -- Function: void mpf_class::mpf_class (const char *S) -- Function: void mpf_class::mpf_class (const char *S, unsigned long PREC, int BASE = 0) -- Function: void mpf_class::mpf_class (const string& S) -- Function: void mpf_class::mpf_class (const string& S, unsigned long PREC, int BASE = 0) Construct an `mpf_class' converted from a string using `mpf_set_str' (*note Assigning Floats::). If PREC is given, the initial precision is that value, in bits. If not, the default `mpf' precision (*note Initializing Floats::) is used. If the string is not a valid float, an `std::invalid_argument' exception is thrown. The same applies to `operator='. -- Function: mpf_class& mpf_class::operator= (type OP) Convert and store the given OP value to an `mpf_class' object. The same types are accepted as for the constructors above. Note that `operator=' only stores a new value, it doesn't copy or change the precision of the destination, instead the value is truncated if necessary. This is the same as `mpf_set' etc. Note in particular this means for `mpf_class' a copy constructor is not the same as a default constructor plus assignment. mpf_class x (y); // x created with precision of y mpf_class x; // x created with default precision x = y; // value truncated to that precision Applications using templated code may need to be careful about the assumptions the code makes in this area, when working with `mpf_class' values of various different or non-default precisions. For instance implementations of the standard `complex' template have been seen in both styles above, though of course `complex' is normally only actually specified for use with the builtin float types. -- Function: mpf_class abs (mpf_class OP) -- Function: mpf_class ceil (mpf_class OP) -- Function: int cmp (mpf_class OP1, type OP2) -- Function: int cmp (type OP1, mpf_class OP2) -- Function: bool mpf_class::fits_sint_p (void) -- Function: bool mpf_class::fits_slong_p (void) -- Function: bool mpf_class::fits_sshort_p (void) -- Function: bool mpf_class::fits_uint_p (void) -- Function: bool mpf_class::fits_ulong_p (void) -- Function: bool mpf_class::fits_ushort_p (void) -- Function: mpf_class floor (mpf_class OP) -- Function: mpf_class hypot (mpf_class OP1, mpf_class OP2) -- Function: double mpf_class::get_d (void) -- Function: long mpf_class::get_si (void) -- Function: string mpf_class::get_str (mp_exp_t& EXP, int BASE = 10, size_t DIGITS = 0) -- Function: unsigned long mpf_class::get_ui (void) -- Function: int mpf_class::set_str (const char *STR, int BASE) -- Function: int mpf_class::set_str (const string& STR, int BASE) -- Function: int sgn (mpf_class OP) -- Function: mpf_class sqrt (mpf_class OP) -- Function: mpf_class trunc (mpf_class OP) These functions provide a C++ class interface to the corresponding GMP C routines. `cmp' can be used with any of the classes or the standard C++ types, except `long long' and `long double'. The accuracy provided by `hypot' is not currently guaranteed. -- Function: mp_bitcnt_t mpf_class::get_prec () -- Function: void mpf_class::set_prec (mp_bitcnt_t PREC) -- Function: void mpf_class::set_prec_raw (mp_bitcnt_t PREC) Get or set the current precision of an `mpf_class'. The restrictions described for `mpf_set_prec_raw' (*note Initializing Floats::) apply to `mpf_class::set_prec_raw'. Note in particular that the `mpf_class' must be restored to it's allocated precision before being destroyed. This must be done by application code, there's no automatic mechanism for it.  File: gmp.info, Node: C++ Interface Random Numbers, Next: C++ Interface Limitations, Prev: C++ Interface Floats, Up: C++ Class Interface 12.5 C++ Interface Random Numbers ================================= -- Class: gmp_randclass The C++ class interface to the GMP random number functions uses `gmp_randclass' to hold an algorithm selection and current state, as per `gmp_randstate_t'. -- Function: gmp_randclass::gmp_randclass (void (*RANDINIT) (gmp_randstate_t, ...), ...) Construct a `gmp_randclass', using a call to the given RANDINIT function (*note Random State Initialization::). The arguments expected are the same as RANDINIT, but with `mpz_class' instead of `mpz_t'. For example, gmp_randclass r1 (gmp_randinit_default); gmp_randclass r2 (gmp_randinit_lc_2exp_size, 32); gmp_randclass r3 (gmp_randinit_lc_2exp, a, c, m2exp); gmp_randclass r4 (gmp_randinit_mt); `gmp_randinit_lc_2exp_size' will fail if the size requested is too big, an `std::length_error' exception is thrown in that case. -- Function: gmp_randclass::gmp_randclass (gmp_randalg_t ALG, ...) Construct a `gmp_randclass' using the same parameters as `gmp_randinit' (*note Random State Initialization::). This function is obsolete and the above RANDINIT style should be preferred. -- Function: void gmp_randclass::seed (unsigned long int S) -- Function: void gmp_randclass::seed (mpz_class S) Seed a random number generator. See *note Random Number Functions::, for how to choose a good seed. -- Function: mpz_class gmp_randclass::get_z_bits (unsigned long BITS) -- Function: mpz_class gmp_randclass::get_z_bits (mpz_class BITS) Generate a random integer with a specified number of bits. -- Function: mpz_class gmp_randclass::get_z_range (mpz_class N) Generate a random integer in the range 0 to N-1 inclusive. -- Function: mpf_class gmp_randclass::get_f () -- Function: mpf_class gmp_randclass::get_f (unsigned long PREC) Generate a random float F in the range 0 <= F < 1. F will be to PREC bits precision, or if PREC is not given then to the precision of the destination. For example, gmp_randclass r; ... mpf_class f (0, 512); // 512 bits precision f = r.get_f(); // random number, 512 bits  File: gmp.info, Node: C++ Interface Limitations, Prev: C++ Interface Random Numbers, Up: C++ Class Interface 12.6 C++ Interface Limitations ============================== `mpq_class' and Templated Reading A generic piece of template code probably won't know that `mpq_class' requires a `canonicalize' call if inputs read with `operator>>' might be non-canonical. This can lead to incorrect results. `operator>>' behaves as it does for reasons of efficiency. A canonicalize can be quite time consuming on large operands, and is best avoided if it's not necessary. But this potential difficulty reduces the usefulness of `mpq_class'. Perhaps a mechanism to tell `operator>>' what to do will be adopted in the future, maybe a preprocessor define, a global flag, or an `ios' flag pressed into service. Or maybe, at the risk of inconsistency, the `mpq_class' `operator>>' could canonicalize and leave `mpq_t' `operator>>' not doing so, for use on those occasions when that's acceptable. Send feedback or alternate ideas to . Subclassing Subclassing the GMP C++ classes works, but is not currently recommended. Expressions involving subclasses resolve correctly (or seem to), but in normal C++ fashion the subclass doesn't inherit constructors and assignments. There's many of those in the GMP classes, and a good way to reestablish them in a subclass is not yet provided. Templated Expressions A subtle difficulty exists when using expressions together with application-defined template functions. Consider the following, with `T' intended to be some numeric type, template T fun (const T &, const T &); When used with, say, plain `mpz_class' variables, it works fine: `T' is resolved as `mpz_class'. mpz_class f(1), g(2); fun (f, g); // Good But when one of the arguments is an expression, it doesn't work. mpz_class f(1), g(2), h(3); fun (f, g+h); // Bad This is because `g+h' ends up being a certain expression template type internal to `gmpxx.h', which the C++ template resolution rules are unable to automatically convert to `mpz_class'. The workaround is simply to add an explicit cast. mpz_class f(1), g(2), h(3); fun (f, mpz_class(g+h)); // Good Similarly, within `fun' it may be necessary to cast an expression to type `T' when calling a templated `fun2'. template void fun (T f, T g) { fun2 (f, f+g); // Bad } template void fun (T f, T g) { fun2 (f, T(f+g)); // Good }  File: gmp.info, Node: BSD Compatible Functions, Next: Custom Allocation, Prev: C++ Class Interface, Up: Top 13 Berkeley MP Compatible Functions *********************************** These functions are intended to be fully compatible with the Berkeley MP library which is available on many BSD derived U*ix systems. The `--enable-mpbsd' option must be used when building GNU MP to make these available (*note Installing GMP::). The original Berkeley MP library has a usage restriction: you cannot use the same variable as both source and destination in a single function call. The compatible functions in GNU MP do not share this restriction--inputs and outputs may overlap. It is not recommended that new programs are written using these functions. Apart from the incomplete set of functions, the interface for initializing `MINT' objects is more error prone, and the `pow' function collides with `pow' in `libm.a'. Include the header `mp.h' to get the definition of the necessary types and functions. If you are on a BSD derived system, make sure to include GNU `mp.h' if you are going to link the GNU `libmp.a' to your program. This means that you probably need to give the `-I' option to the compiler, where `' is the directory where you have GNU `mp.h'. -- Function: MINT * itom (signed short int INITIAL_VALUE) Allocate an integer consisting of a `MINT' object and dynamic limb space. Initialize the integer to INITIAL_VALUE. Return a pointer to the `MINT' object. -- Function: MINT * xtom (char *INITIAL_VALUE) Allocate an integer consisting of a `MINT' object and dynamic limb space. Initialize the integer from INITIAL_VALUE, a hexadecimal, null-terminated C string. Return a pointer to the `MINT' object. -- Function: void move (MINT *SRC, MINT *DEST) Set DEST to SRC by copying. Both variables must be previously initialized. -- Function: void madd (MINT *SRC_1, MINT *SRC_2, MINT *DESTINATION) Add SRC_1 and SRC_2 and put the sum in DESTINATION. -- Function: void msub (MINT *SRC_1, MINT *SRC_2, MINT *DESTINATION) Subtract SRC_2 from SRC_1 and put the difference in DESTINATION. -- Function: void mult (MINT *SRC_1, MINT *SRC_2, MINT *DESTINATION) Multiply SRC_1 and SRC_2 and put the product in DESTINATION. -- Function: void mdiv (MINT *DIVIDEND, MINT *DIVISOR, MINT *QUOTIENT, MINT *REMAINDER) -- Function: void sdiv (MINT *DIVIDEND, signed short int DIVISOR, MINT *QUOTIENT, signed short int *REMAINDER) Set QUOTIENT to DIVIDEND/DIVISOR, and REMAINDER to DIVIDEND mod DIVISOR. The quotient is rounded towards zero; the remainder has the same sign as the dividend unless it is zero. Some implementations of these functions work differently--or not at all--for negative arguments. -- Function: void msqrt (MINT *OP, MINT *ROOT, MINT *REMAINDER) Set ROOT to the truncated integer part of the square root of OP, like `mpz_sqrt'. Set REMAINDER to OP-ROOT*ROOT, i.e. zero if OP is a perfect square. If ROOT and REMAINDER are the same variable, the results are undefined. -- Function: void pow (MINT *BASE, MINT *EXP, MINT *MOD, MINT *DEST) Set DEST to (BASE raised to EXP) modulo MOD. Note that the name `pow' clashes with `pow' from the standard C math library (*note Exponentiation and Logarithms: (libc)Exponents and Logarithms.). An application will only be able to use one or the other. -- Function: void rpow (MINT *BASE, signed short int EXP, MINT *DEST) Set DEST to BASE raised to EXP. -- Function: void gcd (MINT