Fact-checked by Grok 2 weeks ago

GNU Multiple Precision Arithmetic Library

The GNU Multiple Precision Arithmetic Library (GMP), also known as GNU MP, is a free software library that provides for signed integers, rational numbers, and floating-point numbers, enabling computations on numbers with hundreds to millions of digits far beyond the limits of standard . Developed as part of the Project, GMP was originally created by Torbjörn Granlund with its first release in 1991 and has since been maintained by a team of contributors, with the current stable version being 6.3.0, released on July 30, 2023. It is implemented primarily in for portability across various platforms, including support for assembly-optimized code on architectures such as x86, ARM, PowerPC, MIPS, and SPARC, while also offering a C++ class interface for object-oriented use. GMP emphasizes high performance through techniques like fullword arithmetic operations, advanced multiplication algorithms (including Karatsuba, Toom variants, and FFT for very large operands), and minimal function call overhead, making it suitable for demanding applications in , , and scientific research. The library is dual-licensed under the GNU Lesser General Public License version 3 (LGPLv3) and the GNU General Public License version 2 or later (GPLv2+), allowing flexible integration into both free and proprietary software projects.

History and Development

Origins and Initial Development

The GNU Multiple Precision Arithmetic Library (GMP) was initiated in 1991 as part of project, aimed at providing portable capabilities that extend beyond the fixed-size integer limits inherent in standard C programming languages. This effort addressed the need for high-performance numerical computations in fields where precision requirements exceeded hardware-supported bounds. Initial development was led by Torbjörn Granlund, who authored the core library. The project targeted applications in , Internet security protocols, and research, prioritizing efficiency through optimized algorithms and code. Granlund's vision emphasized balancing speed with broad applicability, establishing GMP under the Foundation's from its inception. Early versions focused primarily on integer arithmetic, with an emphasis on portability across systems. Pre-1.0 releases in the early were tested and optimized for architectures such as (both 32-bit and 64-bit variants, including UltraSPARC) and x86, ensuring reliable performance on contemporary hardware platforms. These foundational efforts laid the groundwork for GMP's expansion to support rational and floating-point types in subsequent development.

Releases and Maintenance

The GNU Multiple Precision Arithmetic Library (GMP) had its first official release in 1991, marking the beginning of its availability as a mature tool for developers. Subsequent major versions introduced significant enhancements to functionality and . Version , released in April 1996, added support for arithmetic, expanding GMP's capabilities beyond integers to handle fractions with arbitrary precision. Version 4.0, released in December 2001, focused on optimizations, including improved routines for various architectures to achieve faster computation speeds. Version 5.0, released in January 2010, enhanced 64-bit platform support, providing better compatibility and efficiency on modern 64-bit systems through updated limb handling and assembler code. Version 6.0, released in March 2014, introduced a pivotal licensing change while maintaining with prior series. The latest stable release as of November 2025 is version 6.3.0, issued on July 30, 2023, which primarily addressed bug fixes, minor enhancements to build systems, and support for link-time optimization (LTO) to improve runtime performance without altering the core . GMP follows a maintenance cadence of approximately one new release per year, ensuring ongoing stability and adaptation to evolving hardware and software environments. Originally distributed under the GNU General Public License (GPL), GMP transitioned to a dual licensing model starting with version 6.0, allowing use under either the GNU Lesser General Public License version 3 (LGPLv3) or the GNU GPL version 2. This change facilitates broader integration into both open-source and proprietary projects by permitting dynamic linking without requiring the entire application to be GPL-licensed, while preserving protections for modifications to the library itself. Maintenance of GMP is handled by a dedicated team within the GNU project, with contributions from multiple developers over the years. Notable contributors include Andreas Schwab, who provided key assembly optimizations for architectures like m68k. Development occurs through a repository hosted at gmplib.org, with bug tracking and discussions managed via the project's mailing lists and issue tracker. In 2025, the team issued warnings regarding potential incompatibilities on processors, such as the 9 9950X, where intensive GMP workloads involving tight loops (e.g., using the MULX instruction) have led to excessive power draw, risking CPU damage due to inadequate cooling or under high loads. Users are advised to monitor temperatures and power limits during such computations on affected hardware.

Features and Capabilities

Supported Data Types

The GNU Multiple Precision Arithmetic Library (GMP) provides several core data types designed to handle numbers with arbitrary precision, enabling computations beyond the limits of standard fixed-size types in programming languages like . These types are implemented to support efficient operations on signed integers, rational numbers, and floating-point values, with internal representations that scale dynamically based on available memory. The primary type for arbitrary-precision signed integers is mpz_t, which stores integers as arrays of limbs—each limb being a machine word, typically 32 bits on 32-bit systems or 64 bits on 64-bit systems—allowing for integers of virtually unlimited size limited only by system memory and . There are no inherent upper bounds on the precision of mpz_t beyond these resource constraints, making it suitable for cryptographic applications or large-scale numerical computations requiring thousands or millions of bits. For rational numbers, GMP uses mpq_t, which represents fractions as a pair of mpz_t values for the numerator and denominator, with automatic to ensure the fraction is in lowest terms by computing and dividing out their . This type supports arbitrary in both components, inheriting the scalability of mpz_t while maintaining exact fractional representations without rounding errors inherent in . The mpf_t type handles arbitrary-precision floating-point numbers, configurable at initialization with a specified precision for the (in bits), a base (defaulting to 2^32 per limb), and an exponent range determined by the mp_exp_t type, which is typically a signed long . Precision for the can be set dynamically, but the exponent's range is limited by the size of mp_exp_t, typically supporting exponents up to around ±2^62 on 64-bit systems, ensuring compatibility with scientific computing needs while balancing performance and memory usage. At a lower level, GMP includes the mpn (multiple number) functions, which operate directly on arrays of limbs using the mp_limb_t type for individual machine words and mp_size_t for counting the number of limbs. These are intended for internal use by higher-level functions rather than direct application programming, providing the foundational building blocks for all GMP operations with precision scaled by the array length.

Arithmetic and Utility Functions

The GNU Multiple Precision Arithmetic Library (GMP) provides an extensive set of functions for arbitrary-precision integer arithmetic through the mpz_t type, comprising approximately 150 functions that enable operations on signed integers of unlimited size. Basic arithmetic includes addition (mpz_add), subtraction (mpz_sub), multiplication (mpz_mul), and division variants such as exact division (mpz_divexact) and quotient/remainder computation (mpz_tdiv_q and mpz_tdiv_r). Greatest common divisor calculations are supported via mpz_gcd and extended variants like mpz_gcdext for coefficients. Modular arithmetic functions facilitate modulo a number (mpz_powm) and checks (mpz_congruent_p or mpz_congruent_2exp_p for power-of-2 moduli). operations treat integers as bit vectors, offering logical operations (mpz_and, mpz_ior, mpz_xor), bit shifts (mpz_mul_2exp, mpz_fdiv_q_2exp), and population count (mpz_popcount). Primality testing is available through mpz_probab_prime_p, which employs trial division followed by probabilistic Miller-Rabin tests, returning certainty for small primes and probable primality otherwise. For rational numbers using the mpq_t type, GMP offers around 35 functions focused on exact arithmetic, assuming canonical representation where numerator and denominator share no common factors and the denominator is positive. Arithmetic operations include addition (mpq_add), subtraction (mpq_sub), multiplication (mpq_mul), and division (mpq_div), all of which canonicalize the result automatically. Inversion is provided by mpq_inv, which computes the reciprocal while preserving canonical form. The mpq_canonicalize function explicitly removes common factors from a non-canonical rational, essential after manual assignments to numerator and denominator. Comparisons such as mpq_cmp evaluate equality and ordering, while input/output functions like mpq_inp_str and mpq_out_str handle string conversions in specified bases. Floating-point arithmetic for the mpf_t type, which supports variable-precision binary floating-point numbers, is handled by about 70 functions, emphasizing basic operations with configurable for the . Core arithmetic encompasses (mpf_add), (mpf_sub), (mpf_mul), and (mpf_div), with results rounded to the destination's . is available via mpf_pow_ui for exponents and more general mpf_pow. computation uses mpf_sqrt, and a selection of transcendental functions includes sine (mpf_sin), cosine (mpf_cos), and variants like mpf_sinh. Input and output conversions support string formats (mpf_set_str, mpf_get_str) and interactions with native types like (mpf_get_d, mpf_set_d). Utility functions span all numeric types and include random number generation, special computations, comparisons, and I/O operations. Random integers can be generated uniformly in a range using mpz_urandomm (for mpz_t) or with patterns of zeros and ones via mpz_rrandomb for testing purposes, both requiring an initialized random state (gmp_randstate_t). Special integer functions compute numbers efficiently with mpz_fib_ui or matrix-based mpz_fib2_ui for pairs, and for non-negative integers via mpz_fac_ui. Comparisons are consistent across types, such as mpz_cmp for integers, mpq_cmp for rationals, and mpf_cmp for floats, returning negative, zero, or positive values based on ordering. I/O utilities enable formatted output in bases from 2 to 62, exemplified by mpz_out_str for integers and similar functions for rationals (mpq_out_str) and floats (mpf_out_str). Error handling in GMP relies on function return values rather than exceptions, as the library is designed for C environments without exception support. Most arithmetic functions are void and assume valid inputs, terminating the program on memory allocation failures unless custom allocators are provided; I/O and conversion functions return indicators like the number of bytes processed or -1 on failure.

Internal Implementation

Data Representation and Memory Management

The GNU Multiple Precision Arithmetic Library (GMP) represents multi-precision integers using a sign-magnitude format, where the sign is stored separately from the of the number. The magnitude is encoded as an of limbs, each of type mp_limb_t, which is typically an unsigned type such as unsigned long on most platforms or unsigned long long on systems supporting 64-bit limbs. The number of bits per limb is defined by the constant BITS_PER_MP_LIMB, which is architecture-dependent; for example, it is 64 bits on systems and 32 bits on many 32-bit architectures. The limbs are stored in little-endian order, meaning the least significant limb is at the lowest index (_mp_d[0]), facilitating efficient low-level operations. User-facing variables, such as those of type mpz_t for arbitrary-precision integers, are implemented as structures containing three fields: _mp_alloc (the number of allocated limbs), _mp_size (the actual number of significant limbs, with its sign indicating the number's sign—positive for positive, negative for negative, and zero for zero), and _mp_d (a pointer to the dynamically allocated array of limbs). Memory for the limb array is allocated dynamically using standard C functions like malloc, and GMP automatically reallocates larger blocks when operations require more space, via the internal macro MPZ_REALLOC. At least one limb is always allocated, even for zero, ensuring that functions like mpz_set_ui do not need special handling for small values. Temporary allocations during computations use a separate mechanism, TMP_ALLOC with MPZ_TMP_INIT, to minimize reallocation overhead without affecting persistent variables. At the lowest level, GMP's multiple precision number (mpn) functions operate directly on limb arrays, requiring users to manage pointers, sizes, and allocations explicitly—unlike higher-level mpz functions, which handle memory automatically. These mpn routines process data in little-endian limb order and assume the caller provides sufficient pre-allocated space, returning the actual size used upon completion to allow for normalization (trimming leading zero limbs). GMP has been designed to be reentrant and thread-safe since version 4.0, meaning its functions can be called concurrently from multiple threads without internal state corruption, provided users avoid sharing mutable variables across threads. However, certain configurations (e.g., using --enable-alloca=notreentrant) or legacy functions (e.g., those relying on global state like old generators) may compromise this safety, and I/O operations depend on the underlying C library's reentrancy. Applications must therefore ensure exclusive access to shared GMP objects, such as by using mutexes around operations on the same mpz_t.

Algorithms and Performance Optimizations

The GNU Multiple Precision Arithmetic Library (GMP) employs a hierarchy of multiplication algorithms tailored to operand sizes, transitioning from simple basecase methods for small inputs to advanced techniques for larger ones to optimize computational efficiency. For small operands, basecase multiplication uses straightforward schoolbook methods, performing O(N²) operations where N is the number of limbs. As operand sizes grow beyond the MUL_TOOM22_THRESHOLD (typically around 10-20 limbs depending on the architecture), GMP switches to the Karatsuba algorithm, which reduces the complexity to O(N^{1.585}) by recursively splitting operands into halves and computing three products instead of four. For medium-sized operands, further optimizations employ Toom-Cook variants: Toom-3 (3-way) beyond MUL_TOOM33_THRESHOLD, Toom-4 beyond MUL_TOOM44_THRESHOLD, Toom-6.5 and Toom-8.5 for even larger sizes, and a general Toom-k implementation for unbalanced multiplications where operand lengths differ significantly. These Toom-Cook methods generalize the Karatsuba approach by splitting into k parts, achieving complexities approaching O(N^{1+ε}) for small ε, and are particularly effective in the range where recursion depth is manageable. For very large operands exceeding MUL_FFT_THRESHOLD (often hundreds of limbs), GMP utilizes fast Fourier transform (FFT)-based multiplication, implementing variants of the Schönhage-Strassen algorithm (O(N log N log log N)) and Nussbaumer's method for specific cases, leveraging number-theoretic transforms over rings like Z/(2^{k}+1)Z to handle convolutions efficiently. Division in GMP follows a similar size-dependent strategy, starting with single-limb for the smallest cases using hardware instructions or multiplicative inverses, and basecase for modest sizes, which emulates in 2^{mp_bits_per_limb} with O((N-M)M) , where N and M are and limb counts, respectively; this includes of the divisor and per-limb quotient estimation via 2x1 , followed by subtraction and potential addback corrections. For larger divisors beyond DC_DIV_QR_THRESHOLD (typically 20-50 limbs), a divide-and-conquer approach is employed, recursively reducing a 2N×N to two N×(N/2) divisions using techniques inspired by or the half-Kraitchik method, achieving asymptotic O(M(N) log N) time where M(N) denotes cost; this involves forming the through recursive calls and adjustments, with optimizations for single-limb quotients in the final stages to minimize overhead. Additional specialized divisions include block-wise Barrett reduction for modular operations and exact algorithms that avoid full remainders when divisibility is known, further tuned for in cryptographic contexts. Other core algorithms in GMP also prioritize efficiency through proven methods. The (GCD) computation uses the for very small inputs (under 3 limbs), which iteratively subtracts and shifts to remove factors of 2, achieving roughly 0.68 iterations per bit with O(N²) worst-case complexity but excelling on average due to frequent small quotients. For larger sizes up to GCD_DC_THRESHOLD, Lehmer's algorithm enhances the method by processing only the most significant limbs to predict quotient sequences via a 2x2 , reducing inputs by nearly one limb per step and avoiding full divisions; beyond this threshold, a half-GCD (HGCD) applies subquadratic matrix-based s recursively. Square roots are computed via a divide-and-conquer iteration, splitting the input into quarters and recursively approximating the high parts before adjusting the low , yielding O(M(N)) complexity in the Karatsuba range and leveraging one-limb as the base case for quadratic convergence. Modular exponentiation employs a sliding-window method with window size k adapted to exponent length (e.g., k=1 for , up to k=8 for large exponents), precomputing odd powers to minimize squarings and multiplications, often combined with to eliminate divisions and achieve constant-time properties suitable for . Performance optimizations in GMP are achieved through architecture-specific hand-written code for over 50 CPU families, including x86 (from 386 to modern AVX-enabled), ARM (Cortex-A series), PowerPC, , and others, which implement inner loops for multiplication, division, and other primitives to exploit , SIMD extensions, and cache hierarchies far beyond generic code. Thresholds for algorithm switching (e.g., KARATSUBA_THRESHOLD, FFT_MODF_THRESHOLD) are dynamically tuned during compilation using the tuneup utility, which benchmarks operand sizes on the target hardware to generate an optimized gmp-mparam.h header, ensuring seamless transitions that minimize overhead from or transform setups. These strategies, combined with a portable fallback for unsupported architectures, enable GMP to deliver superior speed for large-integer operations compared to many competitors, such as Java's BigInteger, particularly in FFT-dominated regimes where GMP can be orders of magnitude faster for operands exceeding thousands of bits.

Programming Interface

C API Overview

The GNU Multiple Precision Arithmetic Library (GMP) provides its primary programming interface through the C language, accessible via the header file <gmp.h>. This header declares all necessary types and functions for handling arbitrary-precision integers (mpz_t), rationals (mpq_t), and floating-point numbers (mpf_t), with the integer interface being the most commonly used. Programs must include this header to utilize GMP, and the library is linked during compilation using flags generated by the build process. GMP objects require explicit initialization before use and deallocation afterward to manage efficiently. For integers, mpz_init(mpz_t x) allocates and initializes an mpz_t variable to zero, while mpz_clear(mpz_t x) releases the associated . Similar functions exist for (mpq_init and mpq_clear) and floats (mpf_init and mpf_clear), with variants like mpz_inits for batch initialization of multiple objects. Failure to clear objects can lead to leaks, as GMP dynamically allocates limbs (machine words) as needed during operations. Arithmetic and utility functions follow a consistent prefixed by the type, such as mpz_ for integers. For example, addition is performed with void mpz_add(mpz_t rop, const mpz_t op1, const mpz_t op2), which stores the sum of op1 and op2 in rop. uses mpz_sub, mpz_mul, and mpz_tdiv_q, among others; most such functions take an output first, followed by inputs, and operate in place where possible for efficiency. Utility operations like (mpz_abs) or negation (mpz_neg) also adhere to this pattern. Input and output conversions support flexible string-based import and export in bases from 2 to 62. The function int mpz_set_str(mpz_t rop, const char *str, int base) sets rop from the str in the specified base, ignoring leading whitespace and returning 0 on success or -1 if the string is invalid for that base (with base 0 enabling auto-detection from prefixes like 0x for ). Conversely, char *mpz_get_str(char *str, int base, const mpz_t op) converts op to a in base, allocating memory if str is NULL and returning a pointer to the result; bases 2–36 use digits and letters (case-insensitive), while 37–62 extend to additional uppercase and lowercase letters. GMP's error model is minimalistic, with no signal emissions or aborts on typical failures like invalid inputs; instead, functions that can fail (e.g., string conversions) return an indicator (0 for success, -1 for error), allowing callers to check and handle issues programmatically. Arithmetic functions generally return void and assume valid, initialized operands, with out-of-memory conditions handled by the allocator without raising exceptions. The C API is designed for ANSI C compatibility, ensuring portability across compilers that support the standard. Building GMP and applications uses the GNU autotools suite, starting with the configure script to detect the host system and generate makefiles, followed by make for compilation and make install for deployment (defaulting to /usr/local). This process supports customization via options like --enable-cxx for C++ support, though the core interface remains C-based.

C++ Class Interface

The GNU Multiple Precision Arithmetic Library (GMP) provides an optional C++ class interface that wraps its core C functions in an object-oriented manner, facilitating easier integration into modern C++ programs. This interface, implemented in the separate library libgmpxx, supports arbitrary-precision integers, rationals, and floating-point numbers through dedicated classes, while leveraging for intuitive arithmetic operations. To build GMP with C++ support, the must be invoked with the --enable-cxx option, which compiles the gmpxx.h header and the libgmpxx library. Programs using this interface include the <gmpxx.h> header and link against both -lgmpxx and -lgmp. The primary classes are mpz_class for multiprecision integers, mpq_class for rational numbers, and mpf_class for floating-point values. Each class handles automatic resource management via constructors and destructors, eliminating the need for explicit calls to GMP's C initialization and cleanup functions like mpz_init and mpz_clear. For instance, an mpz_class object can be initialized directly from built-in types, strings, or other GMP objects:
cpp
mpz_class a(123);  // From integer literal
mpz_class b("456", 10);  // From string in base 10
mpz_class c = a * b;  // Overloaded multiplication operator
Arithmetic operators such as +, -, *, /, and % are overloaded for these classes, allowing natural expressions that intermix with C++ built-in types like long or double (with promotion as needed). Comparison operators (==, <, etc.) and functions like abs are also provided, mirroring GMP's C API but with seamless type conversions. Rational numbers via mpq_class automatically canonicalize fractions (reducing numerator and denominator by their GCD), though manual canonicalize() calls may be required after certain input operations to ensure correctness. Floating-point operations in mpf_class respect user-specified precision, set during construction (e.g., mpf_class f(1.23, 128); for 128-bit precision). Input and output integrate with C++ streams for readability. Objects can be streamed to std::ostream (e.g., std::cout << c << std::endl;) or read from std::istream (e.g., std::cin >> a;), with string conversions available via methods like get_str(base) for export in a specified . With compilers, user-defined literals (e.g., 123_mpz for integers or 1.23_mpf for floats) simplify initialization from literals. For invalid string inputs, mpf_class constructors throw std::invalid_argument. Memory allocation failures follow GMP's default error handling, which typically aborts the program unless a custom allocator is installed. The C++ interface maintains compatibility with the underlying C API through accessor methods like get_mpz_t() (returning a const mpz_t&), enabling implicit or explicit passing of class instances to C functions without copying. For example:
cpp
mpz_class x(5), y(3);
mpz_add(x.get_mpz_t(), x.get_mpz_t(), y.get_mpz_t());  // Calls C function directly
However, low-level access to GMP's mpn (multiple precision limbs) functions is not exposed, as the classes abstract away such details. The interface is considered preliminary and may undergo incompatible changes in future GMP releases, with limitations including the need for explicit casts in templated expressions and potential issues with features like auto in expression templates. Subclassing is possible but discouraged due to incomplete support for inherited constructors and assignments.

Language Bindings

Bindings for Common Languages

The GNU Multiple Precision Arithmetic Library (GMP) has been extended to various programming languages through community-developed bindings that wrap its C API, enabling in those ecosystems. These bindings differ in their level of completeness, with some providing full access to GMP's (mpz), rational (mpq), and floating-point (mpf) types, while others focus on subsets or add language-specific conveniences. They are typically implemented using foreign function interfaces or extensions, ensuring compatibility with GMP versions from 5.x onward, though maintenance and performance vary by project. For , the gmpy2 library serves as a mature C-coded extension module that offers comprehensive support for all GMP types, including multiple-precision integers, , real numbers (via MPFR integration), and numbers (via MPC). It emphasizes speed and correct rounding, making it suitable for numerical computations, and is actively maintained with releases compatible with Python 3.x. An alternative, python-gmp, provides lighter GMP-only bindings for users needing solely integer and support. In , the Math::GMP module delivers high-speed arbitrary-precision integer arithmetic as a for the built-in Math::BigInt, with full support for mpz integers and partial support for mpq rationals through related extensions like Math::GMPq. It lacks native floating-point handling but integrates efficiently with Perl's interface for performance-critical tasks. Ruby's gmp gem provides bindings primarily for mpz integers and mpq rationals, allowing seamless integration of GMP's arithmetic operations into Ruby scripts. It supports essential functions like , , and gcd computation, and has been stable since its early versions, though it does not include floating-point support. Rust offers multiple options, with the rug crate acting as a comprehensive, idiomatic high-level wrapper that covers integers, rationals, floating-point numbers, and complex types from GMP, MPFR, and MPC, including features like iterators and safe . For lower-level access, gmp-mpfr-sys provides raw FFI bindings to the C libraries, enabling custom implementations while requiring manual handling of GMP types. Both are actively developed and support recent Rust editions, including 2024. Java developers can use JGMP, a set of JNA-based bindings and wrappers introduced with GMP 6.1, which expose the full to JVM languages like , , and Kotlin. It supports all core types—integers, rationals, and floats—with benchmarks showing near-native performance for large operands. Among other languages, OCaml's MLGMPIDL package offers an interface to nearly all GMP and MPFR functions, supporting integers, rationals, and floats with OCaml's via the OPAM package manager. The programming language's gmp package on CRAN enables big-integer and big-rational operations, including prime testing and computations, tailored for statistical applications. includes an official GMP extension in its core distribution, focusing on arbitrary-precision integers with functions for basic arithmetic and , installable via standard package managers. For C#, the GMP Native Interface library provides P/Invoke-based access to GMP 6.1+ functionality, wrapping integers, rationals, and floats for .NET applications. Overall, these bindings enhance GMP's portability but vary in completeness; for instance, most prioritize integers and , with floating-point support more common in and implementations, and users should consult project for GMP version compatibility.

Integration and Usage in Bindings

Integrating GMP bindings into non-C languages typically involves installing the binding package via language-specific package managers, which in turn requires the underlying GMP to be installed and linked on the system. For , the gmpy2 binding can be installed using with the command pip install gmpy2, provided that GMP version 5.0 or later is available on the system for compilation or linking. Similarly, in , the rug crate is added via with cargo add rug, which depends on GMP through low-level FFI bindings in gmp-mpfr-sys and requires GMP to be present during build. For .NET environments, the Math.Gmp.Native is installed via with Install-Package Math.Gmp.Native.NET, exposing GMP functionality through P/Invoke and .NET types while requiring the GMP DLL to be accessible. In , GMP integration is seamless through built-in support for arbitrary-precision integers via the GNU Multiple Precision Arithmetic Library, leveraging 's base wrapping of GMP without additional installation beyond the . Usage patterns in bindings emphasize creating high-precision types from native language scalars and performing operations idiomatically within the host language. In Python with gmpy2, users import the module and instantiate types such as from gmpy2 import mpz; a = mpz(123); b = a + 456, enabling seamless arithmetic on multi-precision integers that interoperate with Python's built-in int for smaller values. In Rust using rug, the pattern involves importing the crate and constructing values like use rug::Integer; let a = Integer::from(123u32); let b = &a + 456u32, where the Integer type handles promotion to arbitrary precision as needed, integrating with Rust's ownership model for safe memory management. These patterns allow developers to mix GMP operations with native code, often converting back to host types for I/O or further processing. Performance in GMP bindings incurs minimal overhead for large-precision operations, as the core computations delegate directly to GMP's optimized routines via thin wrappers, making the binding layer negligible compared to the algorithmic cost of multi-precision arithmetic. For small numbers fitting within native types (e.g., 64-bit integers), bindings recommend using host language primitives to avoid unnecessary GMP invocation and reduce . Bindings inherit GMP's thread safety characteristics, where operations on distinct variables are reentrant and safe across threads, but simultaneous reads and writes to the same variable require external to prevent data races. Certain bindings exhibit limitations in coverage of GMP's full feature set, such as incomplete support for multiple-precision floating-point (mpf) types; for instance, Perl's Math::GMP module primarily focuses on (mpz) arithmetic for high-speed arbitrary-size operations, offering compatibility with Perl's Math::BigInt but lacking comprehensive mpf or mpc implementations. Cross-language integrations extend GMP's reach, with .NET bindings like Sdcb.Arithmetic providing modern P/Invoke access to GMP and MPFR for C# applications, enabling efficient arbitrary-precision math in managed environments. In , the GMP.jl package facilitates direct use in scientific computing workflows, allowing seamless incorporation of GMP routines alongside Julia's high-performance arrays and numerical tools for tasks like symbolic computation.

Applications and Adoption

Use in Cryptography and Security

The GNU Multiple Precision Arithmetic Library (GMP) is extensively utilized in cryptographic applications for its efficient support of arbitrary-precision integer operations, which are fundamental to public-key cryptosystems including RSA, Diffie-Hellman key exchange, and elliptic curve cryptography. These systems rely on GMP for core computations such as modular exponentiation, implemented via functions like mpz_powm to compute (base^{exponent} \mod modulus) efficiently, and primality testing through mpz_probab_prime_p to generate large primes for key pair creation. By providing high-performance arithmetic without inherent limits beyond memory availability, GMP enables secure handling of the large numbers (often thousands of bits) required to withstand current computational attacks. Several prominent cryptographic libraries incorporate GMP to enhance their big integer capabilities. The Nettle library, a low-level cryptographic toolkit, depends on GMP for bignum operations in implementing primitives like , Diffie-Hellman, , and algorithms. Nettle serves as the cryptographic backend for , a widely adopted library for SSL/TLS and DTLS protocols, thereby leveraging GMP for tasks such as large prime generation and in secure communications. Similarly, OpenSSL supports an optional GMP engine that accelerates multiprecision computations for cryptographic operations when configured with GMP support, though the interface is deprecated since OpenSSL 3.0 (2021) and later versions. In cryptographic research, GMP facilitates the prototyping and performance evaluation of custom protocols, particularly those involving elliptic curves. For instance, software implementations of elliptic curve scalar multiplication over prime fields \mathbb{F}_p commonly employ GMP for finite field arithmetic to achieve efficient point operations essential for key exchange and signatures. The Pairing-Based Cryptography (PBC) library, developed at , builds directly on GMP to support mathematical operations in pairing-based schemes used in advanced protocols like . GMP's emphasizes deterministic , promoting reproducible results that aid in verifying and auditing cryptographic implementations for correctness and . However, as a pure library, it lacks integrated , requiring developers to pair it with external cryptographically secure random sources for operations like prime generation or creation to mitigate predictability risks.

Use in Computer Algebra and Computational Tools

The GNU Multiple Precision Arithmetic Library (GMP) plays a crucial role in computer algebra systems by providing efficient arbitrary-precision integer arithmetic, which is essential for symbolic computations requiring exact results. For instance, Maple integrates GMP directly into its kernel for handling arbitrary-precision integers, enabling high-precision numerical and symbolic operations without overflow limitations. Similarly, Mathematica employs GMP for arithmetic on large integers, particularly those with thousands of digits, to support machine-code optimizations and complex calculations. PARI/GP, a system focused on number theory, leverages GMP as an optional but highly effective multiprecision kernel to accelerate integer operations when available. SageMath, an open-source mathematics software system, uses GMP as a core component for its arbitrary-precision integer arithmetic, enabling efficient symbolic and numerical computations. In compilers, GMP facilitates advanced optimizations involving large constants. The GNU Compiler Collection (GCC) depends on GMP for multiprecision arithmetic during and evaluation of big integer literals, ensuring accurate handling of expressions that exceed native integer sizes. GMP's exact arithmetic capabilities extend to through libraries like (Computational Geometry Algorithms Library), which optionally uses GMP to implement exact predicates and constructions. This integration allows for robust geometric computations that avoid floating-point errors, such as orientation tests and intersection calculations in higher dimensions. In broader scientific computing, tools like Maxima benefit from GMP when built with Lisp implementations that incorporate it for arbitrary-precision support, aiding symbolic manipulation in domains like . Overall, GMP's adoption in these systems enables precise, scalable computations beyond the limits of fixed-precision , supporting applications in exact symbolic and theoretical .

References

  1. [1]
    The GNU MP Bignum Library
    GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating-point numbers, designed to be fast.GMP manual · GMP 6.3 release notes · GMP Repository Usage
  2. [2]
    Introduction to GMP (GNU MP 6.3.0)
    GNU MP is a portable library written in C for arbitrary precision arithmetic on integers, rational numbers, and floating-point numbers.
  3. [3]
    Contributors (GNU MP 6.3.0)
    Torbjörn Granlund wrote the original GMP library and is still the main developer. Code not explicitly attributed to others was contributed by Torbjörn.
  4. [4]
    GMP 6.3.0 released - GNU MP
    Jul 30, 2023 · A new release of the GNU Multiple Precision Arithmetic Library (GMP) is now available. The new release is identified as 6.3.0.
  5. [5]
    Multiplication Algorithms (GNU MP 6.3.0)
    GNU MP uses Karatsuba, Toom-3, Toom-4, Toom-6.5, Toom-8.5, and FFT algorithms for multiplication, with special Toom-inspired algorithms for unbalanced ...
  6. [6]
    [PDF] gmp-man-6.3.0.pdf - GNU MP
    Jul 29, 2023 · GNU MP is a portable library written in C for arbitrary precision arithmetic on integers, rational numbers, and floating-point numbers. It aims ...
  7. [7]
    Index of /gnu/gmp
    Index of /gnu/gmp ; [ ], gmp-3.0.tar.gz, 2000-04-18 13:12 ; [ ], gmp-3.1.1.tar.gz, 2000-10-13 13:53 ; [ ], gmp-3.1.tar.gz, 2000-08-03 13:40 ...
  8. [8]
    GNU MP 2.0.2 - Rational Number Functions
    Rational numbers are stored in objects of type mpq_t . All rational arithmetic functions assume operands have a canonical form, and canonicalize their result.
  9. [9]
    GMP 5.0 News
    IBM S/390 are now supported in both 31/32-bit and 64-bit mode. (We have not been able to fully test this on any multilib machine, since IBM expired our guest ...
  10. [10]
    GMP 5.0.0 released! - GNU MP
    Sep 8, 2011 · GMP 5.0.0 released! Torbjorn Granlund tg at gmplib.org. Fri Jan 8 13:02:16 CET 2010. Next message: GMP 4.3.2 released! Messages sorted by ...GMP 5.0.1 released! - GNU MPGMP 5.0.2 released! - GNU MPMore results from gmplib.org
  11. [11]
    GMP 6.0.0 released - GNU MP
    Mar 25, 2014 · A new major release of the GNU Multiple Precision Arithmetic Library (GMP) is now available. The new release is identified as 6.0.0.New GMP releaseGMP 6.1.0 releasedMore results from gmplib.org
  12. [12]
    GMP 6.3 News
    GMP 6.3 is upwardly source and binary compatible with 6.2, 6.1, 6.0, 5.1, 5.0, 4.x, and 3.x, except for applications that use the semi-documented mpn_bdivmod<|control11|><|separator|>
  13. [13]
    GMP 6.0 News - GNU MP
    GMP 6.0 is upwardly source and binary compatible with 5.1, 5.0, 4.x, and 3.x, except for applications that use the semi-documented mpn_bdivmod function.
  14. [14]
    GMP damaging Zen 5 CPUs? - GNU MP
    Aug 24, 2025 · It might be that the Zen 5 CPUs pull more power than specified when running GMP, or it might be that our cooling solutions are inadequate. The ...Missing: management | Show results with:management
  15. [15]
    Nomenclature and Types (GNU MP 6.3.0)
    GMP uses `mpz_t` for integers, `mpq_t` for rational numbers, `mpf_t` for floating point numbers, and `mp_limb_t` for limbs. `mp_size_t` is for counts of limbs.
  16. [16]
    Internals (GNU MP 6.3.0)
    This chapter is provided only for informational purposes and the various internals described here may change in future GMP releases. ... Integer Internals ...
  17. [17]
    Function Classes (GNU MP 6.3.0)
    Functions for signed integer arithmetic, with names beginning with mpz_ . The associated type is mpz_t . There are about 150 functions in this class.<|separator|>
  18. [18]
    Integer Arithmetic (GNU MP 6.3.0)
    5.5 Arithmetic Functions · Function: void mpz_add (mpz_t rop , const mpz_t op1 , const mpz_t op2 ) ¶ · Function: void mpz_sub (mpz_t rop , const mpz_t op1 , const ...
  19. [19]
    Number Theoretic Functions (GNU MP 6.3.0)
    These functions are designed for calculating isolated Fibonacci numbers. When a sequence of values is wanted it's best to start with mpz_fib2_ui and iterate ...
  20. [20]
    Integer Logic and Bit Fiddling (GNU MP 6.3.0)
    5.11 Logical and Bit Manipulation Functions. These functions behave as if two's complement arithmetic were used (although sign-magnitude is the actual ...
  21. [21]
    Prime Testing Algorithm (GNU MP 6.3.0)
    15.7.1 Prime Testing. The primality testing in mpz_probab_prime_p (see Number Theoretic Functions) first does some trial division by small factors and then ...
  22. [22]
    Rational Arithmetic (GNU MP 6.3.0)
    6.3 Arithmetic Functions. Function: void mpq_add (mpq_t sum , const mpq_t addend1 , const mpq_t addend2 ) ¶. Set sum to addend1 + addend2 .
  23. [23]
    Rational Number Functions (GNU MP 6.3.0)
    This chapter describes the GMP functions for performing arithmetic on rational numbers. These functions start with the prefix mpq_.
  24. [24]
    Comparing Rationals (GNU MP 6.3.0)
    6.4 Comparison Functions​​ Return a positive value if op1 > op2 , zero if op1 = op2 , and a negative value if op1 < op2 . To determine if two rationals are equal ...
  25. [25]
    I/O of Rationals (GNU MP 6.3.0)
    6.6 Input and Output Functions. Functions that perform input from a stdio stream, and functions that output to a stdio stream, of mpq numbers.
  26. [26]
    Float Arithmetic (GNU MP 6.3.0)
    This lets the user handle arithmetic exceptions in these functions in the same manner as other arithmetic exceptions.
  27. [27]
    Floating-point Functions (GNU MP 6.3.0)
    7 Floating-point Functions. GMP floating point numbers are stored in objects of type mpf_t and functions operating on them have an mpf_ prefix.
  28. [28]
    I/O of Floats (GNU MP 6.3.0)
    7.7 Input and Output Functions. Functions that perform input from a stdio stream, and functions that output to a stdio stream, of mpf numbers.
  29. [29]
    Converting Floats (GNU MP 6.3.0)
    7.4 Conversion Functions. Function: double mpf_get_d (const mpf_t op ) ¶. Convert op to a double , truncating if necessary (i.e. rounding towards zero).
  30. [30]
    Integer Random Numbers (GNU MP 6.3.0)
    Generate a random integer with long strings of zeros and ones in the binary representation. Useful for testing functions and algorithms.
  31. [31]
    Integer Comparisons (GNU MP 6.3.0)
    Compare op1 and op2. Return a positive value if op1 > op2, zero if op1 = op2, or a negative value if op1 < op2.
  32. [32]
    Float Comparison (GNU MP 6.3.0)
    Compare op1 and op2. Return a positive value if op1 > op2, zero if op1 = op2, and a negative value if op1 < op2.
  33. [33]
    Miscellaneous Integer Functions (GNU MP 6.3.0)
    Return the size of op measured in number of digits in the given base . base can vary from 2 to 62. The sign of op is ignored, just the absolute value is used.
  34. [34]
    Custom Allocation (GNU MP 6.3.0)
    By default GMP uses malloc, realloc and free for memory allocation, and if they fail GMP prints a message to the standard error output and terminates the ...
  35. [35]
    Integer Internals (GNU MP 6.3.0)
    16.1 Integer Internals. mpz_t variables represent integers using sign and magnitude, in space dynamically allocated and reallocated.
  36. [36]
    Reentrancy (GNU MP 6.3.0)
    3.7 Reentrancy​​ GMP is reentrant and thread-safe, with some exceptions: If configured with --enable-alloca=malloc-notreentrant (or with --enable-alloca= ...
  37. [37]
  38. [38]
    Basecase Division (GNU MP 6.3.0)
    Basecase NxM division is like long division done by hand, but in base 2^mp_bits_per_limb. See Knuth section 4.3.1 algorithm D, and mpn/generic/sb_divrem_mn.c .
  39. [39]
    Divide and Conquer Division (GNU MP 6.3.0)
    The algorithm consists essentially of recognising that a 2NxN division can be done with the basecase division algorithm (see Basecase Division), but using N/2 ...
  40. [40]
    Division Algorithms (GNU MP 6.3.0)
    15.2 Division Algorithms. Single Limb Division · Basecase Division · Divide and Conquer Division · Block-Wise Barrett Division · Exact Division ...
  41. [41]
    Binary GCD (GNU MP 6.3.0)
    It simply consists of successively reducing odd operands a and b using a,b = abs(ab),min(a,b) strip factors of 2 from a.
  42. [42]
    None
    Nothing is retrieved...<|separator|>
  43. [43]
    Square Root Algorithm (GNU MP 6.3.0)
    The square root of the high two parts is taken, by recursive application of the algorithm (bottoming out in a one-limb Newton's method),. s1,r1 = sqrtrem (a3 ...Missing: iteration | Show results with:iteration
  44. [44]
    Modular Powering Algorithm (GNU MP 6.3.0)
    Modular powering is implemented using a 2^k-ary sliding window algorithm, as per “Handbook of Applied Cryptography” algorithm 14.85.Missing: windowing | Show results with:windowing
  45. [45]
    Performance optimization (GNU MP 6.3.0)
    If you're going to use GMP for extremely large numbers, you may want to run tuneup with a large NNN value.Missing: threshold | Show results with:threshold
  46. [46]
    Build Options (GNU MP 6.3.0)
    It actually allocates just small blocks on the stack; larger ones use malloc-reentrant. ' malloc-reentrant ' is, as the name suggests, reentrant and thread safe ...
  47. [47]
  48. [48]
    Initializing Integers (GNU MP 6.3.0)
    The functions for integer arithmetic assume that all integer objects are initialized. You do that by calling the function mpz_init.Missing: interface | Show results with:interface
  49. [49]
  50. [50]
    Converting Integers (GNU MP 6.3.0)
    Functions for converting to GMP integers are described in Assignment Functions and Input and Output Functions. Return the value of op as an unsigned long .
  51. [51]
    GNU MP 4.1
    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. #include <gmp.h>. Note ...<|control11|><|separator|>
  52. [52]
  53. [53]
    C++ Interface General (GNU MP 6.3.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 ...
  54. [54]
    12.2 C++ Interface Integers - mpz_class - GNU MP
    These functions provide a C++ class interface to the corresponding GMP C routines. Calling factorial or primorial on a negative number is undefined.
  55. [55]
    C++ Interface Rationals (GNU MP 6.3.0)
    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 ...
  56. [56]
    C++ Interface Floats (GNU MP 6.3.0)
    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 ...
  57. [57]
    C++ Class Interface (GNU MP 6.3.0)
    This chapter describes the C++ class based interface to GMP. All GMP C language types and functions can be used in C++ programs.
  58. [58]
    C++ Interface Limitations (GNU MP 6.3.0)
    There's many of those in the GMP classes, and a good way to reestablish them in a subclass is not yet provided.
  59. [59]
    Language Bindings (GNU MP 6.3.0)
    How to install and use the GNU multiple precision arithmetic library, version 6.3.0.Missing: Multiple | Show results with:Multiple<|control11|><|separator|>
  60. [60]
    Overview — gmpy2 2.2.2a1 documentation - Read the Docs
    In case you are interested only in the GMP bindings, you can use the python-gmp package. The mpfr and mpc types provide support for correctly rounded ...
  61. [61]
    Math::GMP - High speed arbitrary size integer math - metacpan.org
    Math::GMP was designed to be a drop-in replacement both for Math::BigInt and for regular integer arithmetic.
  62. [62]
    rug - Rust - Docs.rs
    Rug is a high-level interface to the following GNU libraries: GMP for integers and rational numbers,; MPFR for floating-point numbers, and; MPC for complex ...
  63. [63]
    gmp-mpfr-sys — system library interface for Rust // Lib.rs
    The gmp-mpfr-sys crate provides Rust FFI bindings to the following GNU arbitrary-precision libraries: GMP for integers and rational numbers,; MPFR for floating- ...<|separator|>
  64. [64]
    jandom-devel/JGMP: Java bindings for the GMP (GNU ... - GitHub
    The library has bindings for many programming languages, including . NET, OCaml, Perl, PHP, Python, R, Ruby, and Rust, with the notable exception of Java.
  65. [65]
    opam - mlgmpidl - OCaml
    Feb 9, 2024 · Documentation on ocaml.org. OCaml interface to the GMP library. Authors, Bertrand Jeannet and Nicolas Berthier. License, LGPL-2.1-only WITH ...
  66. [66]
    [PDF] gmp: Multiple Precision Arithmetic
    Aug 23, 2024 · Addition, subtraction, multiplication, division, and absolute value for large rationals, i.e. "bigq" class R objects. Usage add.bigq(e1, e2). ## ...
  67. [67]
    GMP - Manual - PHP
    Be careful with GMP - it considers leading zeros in a number string as meaning the number is in octal, whereas 'bc' doesn't.
  68. [68]
    Welcome to the GMP Native Interface for .NET Library - GitHub Pages
    It is based on the GNU MP "fat" build which automatically detects the current CPU type, and selects any available assembly language code optimization for that ...
  69. [69]
  70. [70]
    Nettle: a low-level cryptographic library - Lysator
    The libhogweed library contains those functions of Nettle that uses bignum operations, and depends on the GMP library. With this division, linking works the ...
  71. [71]
    2 Introduction to GnuTLS
    The “Cryptographic back-end” is provided by the nettle and gmplib libraries. • Downloading and installing. • Installing for a software distribution. • Document ...
  72. [72]
    Software Implementation of ECC Using GMP Library - ResearchGate
    PDF | —This paper presents an efficient software implementation of elliptic curve scalar multiplication. Computing kP need finite field point operations.
  73. [73]
    PBC Library - Pairing-Based Cryptography - About
    The PBC (Pairing-Based Cryptography) library is a free C library built on the GMP library that performs the mathematical operations underlying pairing-based ...Missing: notable | Show results with:notable
  74. [74]
    Top (GNU MP 6.3.0)
    This manual describes how to install and use the GNU multiple precision arithmetic library, version 6.3.0.Introduction to GNU MP · Installing GMP · C++ Class Interface · Integer Functions
  75. [75]
  76. [76]
    [PDF] The Mathematica Kernel: Issues in the Design and Implementation
    ... (GMP) library was similarly more efficient for arithmetic of numbers with many (thousands or more digits). We made accomodations to use GMP in many places ...
  77. [77]
    cite PARI - PARI/GP Development Headquarters
    Sep 28, 2025 · PARI multiprecision kernel can use native implementations or make good use of GMP if it is available. We advise you to download and install GMP ...
  78. [78]
    CGAL 6.1 - 2D and 3D Linear Geometry Kernel: User Manual
    CGAL, the Computational Geometry Algorithms Library, is written in C++ and consists of three major parts. The first part is the kernel, which consists of ...
  79. [79]
    [Maxima-discuss] GMP or Flint
    Apr 22, 2023 · There are a couple of threads on the list discussing the use of GMP within Maxima based on the fact that some Lisps have GMP already ...