gmp clib Mathematics / Arithmetic

GNU arbitrary precision arithmetic for PascalAI. BigInt, BigRat, BigFloat — exact integers of unlimited size, exact fractions, and arbitrary-precision floating point. Cryptography, number theory, modpow, primality testing, factorial.

ppm install gmp

Overview

gmp wraps libgmp — the GNU Multiple Precision Arithmetic Library, the de facto standard for arbitrary-precision computation. Numbers have no fixed size limit; they grow as large as memory allows. All integer and rational operations are exact: no rounding, no overflow.

GMP uses highly optimized algorithms internally: Karatsuba multiplication, Toom-Cook 3-way, and FFT-based multiplication for very large numbers. The library automatically selects the best algorithm based on operand size, so you get near-optimal performance without any tuning.

CLib package

Requires libgmp-dev. Ubuntu/Debian: sudo apt install libgmp-dev

Numeric Types

PascalAI typeGMP typeDescriptionUse case
TBigIntmpz_tArbitrary-precision signed integer. Exact, unlimited range.Cryptography, factorials, Fibonacci, number theory
TBigRatmpq_tExact rational number stored as numerator/denominator pair. Always kept in lowest terms.Financial exact arithmetic, symbolic computation, fractions
TBigFloatmpf_tArbitrary-precision binary floating-point. Precision (in bits) is set at creation.High-precision scientific computation, pi calculation, custom precision
Performance note

For numbers smaller than ~128 bits, GMP has overhead compared to native Int64 — prefer built-in types for small values. For 256+ bits, GMP is much faster than any pure-Pascal implementation. A 1000-digit multiplication takes approximately 10 µs on modern hardware.

Use Cases

DomainExample
CryptographyRSA key generation and encryption (modpow), Diffie-Hellman parameter generation, primality testing for key primes
Number theoryGCD, LCM, modular inverse, next prime, primality proofs, Fibonacci(1 000 000)
Exact arithmeticRational arithmetic with no floating-point rounding; financial calculations requiring exact fractions
Arbitrary calculatorsFactorial(10000), arbitrary-base conversions, symbolic math engines
Competitive programmingLarge number problems where overflow would otherwise require special-casing

Comparison

LibraryNotes
vs Python intGMP is the C library CPython's arbitrary-precision integers use internally. Same algorithms, direct C speed.
vs Java BigIntegerGMP is faster; Java BigInteger uses similar algorithms but with JVM overhead. GMP is the gold standard.
vs MPFRMPFR wraps GMP and adds correctly-rounded results for transcendental functions (sin, exp, log). Use MPFR when you need IEEE-style rounding guarantees for floats.

Quick Start

RSA-style modular exponentiation

uses gmp;

{ Compute ciphertext = message^exponent mod modulus }
var msg := NewIntStr('42', 10);
var exp := NewIntStr('65537', 10);
var modulus := NewIntStr('999999999999999989', 10);
var result := NewInt();

IntPowMod(result, msg, exp, modulus);
WriteLn('Ciphertext: ' + IntToStr(result, 10));

FreeInt(msg);
FreeInt(exp);
FreeInt(modulus);
FreeInt(result);

Factorial of 1000 (one-shot string helper)

uses gmp;

var s := FactorialStr(1000);
WriteLn('1000! has ' + IntToStr(Length(s)) + ' digits');
WriteLn('First 40 digits: ' + Copy(s, 1, 40));

Rational arithmetic: 1/3 + 1/6 = 1/2

uses gmp;

var a := NewRatVal(1, 3);   { 1/3 }
var b := NewRatVal(1, 6);   { 1/6 }
var r := NewRat();

RatAdd(r, a, b);
WriteLn('1/3 + 1/6 = ' + RatToStr(r));   { prints "1/2" }

FreeRat(a);
FreeRat(b);
FreeRat(r);

Primality test

uses gmp;

var candidate := NewIntStr('32416190071', 10);
var verdict := IntIsPrime(candidate, 25);   { 25 Miller-Rabin rounds }

if verdict = 2 then
  WriteLn('Definitely prime')
else if verdict = 1 then
  WriteLn('Probably prime')
else
  WriteLn('Composite');

FreeInt(candidate);

TBigInt API

Create / destroy

FunctionDescription
NewInt(): TBigIntCreate a BigInt initialized to 0
NewIntVal(V: Int64): TBigIntCreate a BigInt from a native 64-bit integer
NewIntStr(S, Base): TBigIntCreate a BigInt by parsing a string in the given base (2–62)
FreeInt(N)Release the BigInt and its memory
IntSet(N, V: Int64)Assign an Int64 value to an existing BigInt
IntSetStr(N, S, Base)Assign a string value to an existing BigInt
IntToStr(N, Base): stringConvert to string in the given base
IntToInt64(N): Int64Convert to Int64 (truncates if the value exceeds 64 bits)

Arithmetic

FunctionDescription
IntAdd(R, A, B)R := A + B
IntSub(R, A, B)R := A − B
IntMul(R, A, B)R := A × B
IntDiv(Q, R, A, B)Q := A div B, R := A mod B (quotient and remainder)
IntMod(R, A, B)R := A mod B
IntPow(R, Base, Exp: Int64)R := Base ^ Exp (integer exponentiation)
IntNeg(R, A)R := −A
IntAbs(R, A)R := |A|
IntSqrt(R, A)R := floor(sqrt(A)) (integer square root)
IntCmp(A, B): IntegerCompare: returns −1, 0, or +1
IntCmpInt64(A, B: Int64): IntegerCompare BigInt to a native Int64
IntSign(N): IntegerReturns −1, 0, or +1 for the sign

Number theory

FunctionDescription
IntGCD(R, A, B)R := greatest common divisor of A and B
IntLCM(R, A, B)R := least common multiple of A and B
IntPowMod(R, Base, Exp, Mod)R := Base^Exp mod Mod — fast modular exponentiation for cryptography
IntInvert(R, A, Mod): BooleanR := A¹ mod Mod. Returns False if the modular inverse does not exist.
IntIsPrime(N, Reps): IntegerMiller-Rabin primality test with Reps rounds. Returns 2=prime, 1=probably prime, 0=composite.
IntNextPrime(R, N)R := smallest prime greater than N
IntBitLength(N): IntegerNumber of bits needed to represent N

Bitwise operations

FunctionDescription
IntAnd(R, A, B)R := A and B (bitwise AND)
IntOr(R, A, B)R := A or B (bitwise OR)
IntXor(R, A, B)R := A xor B (bitwise XOR)
IntShl(R, A, Bits)R := A shl Bits (left shift)
IntShr(R, A, Bits)R := A shr Bits (right shift)

TBigRat API

Rationals are always stored and displayed in lowest terms. GMP automatically reduces the fraction after every arithmetic operation.

FunctionDescription
NewRat(): TBigRatCreate a rational initialized to 0/1
NewRatVal(Num, Den: Int64): TBigRatCreate a rational from numerator and denominator
FreeRat(R)Release the rational and its memory
RatToStr(R): stringConvert to string in num/den form
RatToDouble(R): DoubleConvert to Double (approximate; may lose precision)
RatAdd(R, A, B)R := A + B
RatSub(R, A, B)R := A − B
RatMul(R, A, B)R := A × B
RatDiv(R, A, B)R := A / B
RatCmp(A, B): IntegerCompare: returns −1, 0, or +1

TBigFloat API

BigFloat uses binary floating point, not decimal. The precision is specified in bits at creation time. Unlike TBigRat, BigFloat operations may introduce rounding at the specified precision boundary.

FunctionDescription
NewFloat(Prec: Integer): TBigFloatCreate a BigFloat with Prec bits of precision
NewFloatVal(V: Double; Prec): TBigFloatCreate from a Double with the given precision
FreeFloat(F)Release the BigFloat and its memory
FloatToStr(F, Digits): stringConvert to string with Digits significant decimal digits
FloatToDouble(F): DoubleConvert to Double (approximate)
FloatAdd(R, A, B)R := A + B
FloatSub(R, A, B)R := A − B
FloatMul(R, A, B)R := A × B
FloatDiv(R, A, B)R := A / B
FloatSqrt(R, A)R := sqrt(A)
FloatCmp(A, B): IntegerCompare: returns −1, 0, or +1

Convenience Helpers

These one-shot functions accept and return decimal strings directly, avoiding manual handle management. Ideal for quick computations where you only need the result as text.

FunctionDescription
AddStr(A, B: string): stringAdd two decimal integer strings and return the result
MulStr(A, B: string): stringMultiply two decimal integer strings and return the result
PowStr(Base: string; Exp: Int64): stringCompute Base^Exp as a decimal string
FactorialStr(N: Int64): stringCompute N! as a decimal string
GCDStr(A, B: string): stringCompute GCD of two decimal integer strings
uses gmp;

{ No handles, no Free calls needed }
WriteLn(MulStr('123456789012345678901234567890',
                '987654321098765432109876543210'));
WriteLn(GCDStr('3456789', '1234567'));
WriteLn(PowStr('2', 100));   { 2^100 }

Utility

FunctionDescription
GMPVersion(): stringReturns the linked GMP library version string (e.g. "6.3.0")
Memory management

Every NewInt, NewRat, and NewFloat call allocates memory inside GMP. Always call the matching FreeInt / FreeRat / FreeFloat when you are done. The convenience string helpers (AddStr, FactorialStr, etc.) manage their own memory internally.

Package Info

Version1.0.0
Typeclib
C Librarylibgmp-dev
Authorgustavo

System Requirements

libgmp-dev

Ubuntu/Debian:
sudo apt install libgmp-dev

Algorithms

GMP selects automatically:

Karatsuba — medium integers
Toom-Cook 3-way — large integers
FFT multiplication — very large (1000+ digits)

Miller-Rabin for primality with configurable rounds.

Functions

  • NewInt / NewIntVal / NewIntStr
  • FreeInt
  • IntSet / IntSetStr
  • IntToStr / IntToInt64
  • IntAdd / IntSub / IntMul
  • IntDiv / IntMod / IntPow
  • IntNeg / IntAbs / IntSqrt
  • IntCmp / IntCmpInt64 / IntSign
  • IntGCD / IntLCM
  • IntPowMod / IntInvert
  • IntIsPrime / IntNextPrime
  • IntBitLength
  • IntAnd / IntOr / IntXor
  • IntShl / IntShr
  • NewRat / NewRatVal / FreeRat
  • RatToStr / RatToDouble
  • RatAdd / RatSub / RatMul / RatDiv
  • RatCmp
  • NewFloat / NewFloatVal / FreeFloat
  • FloatToStr / FloatToDouble
  • FloatAdd / FloatSub / FloatMul / FloatDiv
  • FloatSqrt / FloatCmp
  • AddStr / MulStr / PowStr
  • FactorialStr / GCDStr
  • GMPVersion

See Also