Math::GMP(3pm)
๐ธ Math::GMP โ part 1, bestie ๐ธ
okay so this is the Math::GMP(3pm) page from the User Contributed Perl Documentation. It's a long one so we're splitting it โ this is part 1 and more is coming, don't go anywhere ๐
โจ NAME โจ
Math::GMP โ High speed arbitrary size integer math ๐งฎโจ
๐ VERSION ๐
version 2.25
๐ SYNOPSIS ๐
use Math::GMP;
my $n = Math::GMP->new('2');
$n = $n ** (256*1024);
$n = $n - 1;
print "n is now $n\n";
๐ DESCRIPTION ๐
So Math::GMP was literally designed to be a drop-in replacement for both Math::BigInt and regular integer arithmetic. But unlike BigInt, it runs all of its calculations through the GNU gmp library instead of straight Perl functions. And that? That means speed improvements ๐ฅ
The downside bestie: this module needs a C compiler to install โ a small tradeoff in most cases tbh. Also, heads up, this module is not 100% compatible with Math::BigInt. Just so you know ๐ซถ
A Math::GMP object can be used exactly like a normal numeric scalar would be โ the module overloads most of the normal arithmetic operators so the interface feels as seamless as possible. But if you want a perfect interface, do this:
use Math::GMP qw(:constant);
$n = 2 ** (256 * 1024);
print "n is $n\n";
This would fail without the :constant, because Perl would use normal doubles to compute the 250,000 bit number, and thereby overflow it into meaninglessness (smaller exponents yield less accurate data due to floating point rounding). ๐
๐ METHODS ๐
The non-overload interface isn't complete, but bestie, the following functions do exist:
๐ฆ new
$x = Math::GMP->new(123);
Creates a new Math::GMP object from the string or scalar you hand it. Easy ๐
$x = Math::GMP->new('abcd', 36);
Creates a new Math::GMP object from the first param โ which should be represented in the base given by the second param. Slay.
๐ฆ bfac
$x = Math::GMP->new(5);
my $val = $x->bfac(); # 1*2*3*4*5 = 120
print $val;
Calculates the factorial of $x and returns the result. Iconic behavior honestly.
๐ฆ $n->bnok($k)
$x = Math::GMP->new(5);
my $val = $x->bnok(2); # 1*2*3*4*5/(1*2)/(1*2*3) = 10
print $val;
Calculates the binomial coefficient of $n over $k and returns the result. It equals $n!/($k!*($n-$k)!). ๐
( Added in version 2.23 .)
๐ฆ my $val = $x->band($y, $swap)
$x = Math::GMP->new(6);
my $val = $x->band(3, 0); # 0b110 & 0b11 = 1
print $val;
Calculates the bit-wise AND of its two arguments and returns the result. $swap should be provided but is ignored (yes, really).
๐ฆ my $ret = $x->bxor($y, $swap);
$x = Math::GMP->new(6);
my $val = $x->bxor(3, 0); # 0b110 ^ 0b11 = 0b101
print $val;
Calculates the bit-wise XOR of its two arguments and returns the result.
๐ฆ my $ret = $x->bior($y, $swap);
$x = Math::GMP->new(6);
my $val = $x->bior(3); # 0b110 | 0b11 = 0b111
print $val;
Calculates the bit-wise OR of its two arguments and returns the result.
๐ฆ blshift
$x = Math::GMP->new(0b11);
my $result = $x->blshift(4, 0);
# $result = 0b11 << 4 = 0b110000
Calculates the bit-wise left-shift of its two arguments and returns the result. The second argument is swap.
๐ฆ brshift
$x = Math::GMP->new(0b11001);
my $result = $x->brshift(3, 0);
# $result = 0b11001 << 3 = 0b11
Calculates the bit-wise right-shift of its two arguments and returns the result. The second argument is swap.
๐ฆ bgcd
my $x = Math::GMP->new(6);
my $gcd = $x->bgcd(4);
# 6 / 2 = 3, 4 / 2 = 2 => 2
print $gcd
Returns the Greatest Common Divisor of the two arguments. math girlies rise ๐ซถ
๐ฆ blcm
my $x = Math::GMP->new(6);
my $lcm = $x->blcm(4); # 6 * 2 = 12, 4 * 3 = 12 => 12
print $lcm;
Returns the Least Common Multiple of the two arguments. periodt.
๐ฆ bmodinv
my $x = Math::GMP->new(5);
my $modinv = $x->bmodinv(7); # 5 * 3 == 1 (mod 7) => 3
print $modinv;
Returns the modular inverse of $x (mod $y), if defined. Right now it returns 0 if there's no inverse (but that may change in the future, so don't hardcode your life around it). When $y is 0, the behaviour is undefined โ do not play with that.
๐ฆ broot
my $x = Math::GMP->new(100);
my $root = $x->root(3); # int(100 ** (1/3)) => 4
print $root;
Returns the integer n'th root of its argument, given a positive integer n.
๐ฆ brootrem
my $x = Math::GMP->new(100);
my($root, $rem) = $x->rootrem(3); # 4 ** 3 + 36 = 100
print "$x is $rem more than the cube of $root";
Returns the integer n'th root of its argument, and the difference such that $root ** $n + $rem == $x.
๐ฆ bsqrt
my $x = Math::GMP->new(6);
my $root = $x->bsqrt(); # int(sqrt(6)) => 2
print $root;
Returns the integer square root of its argument.
๐ฆ bsqrtrem
my $x = Math::GMP->new(7);
my($root, $rem) = $x->sqrtrem(); # 2 ** 2 + 3 = 7
print "$x is $rem more than the square of $root";
Returns the integer square root of its argument, and the difference such that $root ** 2 + $rem == $x.
๐ฆ is_perfect_power
my $x = Math::GMP->new(100);
my $is_power = $x->is_perfect_power();
print "$x is " . ($is_power ? "" : "not ") . "a perfect power";
Returns TRUE if its argument is a power โ like, if there exist integers a and b with b > 1 such that $x == $a ** $b.
๐ฆ is_perfect_square
my $x = Math::GMP->new(100);
my $is_square = $x->is_perfect_square();
print "$x is " . ($is_square ? "" : "not ") . "a perfect square";
Returns TRUE if its argument is the square of an integer. ๐ช
๐ฆ legendre
$x = Math::GMP->new(6);
my $ret = $x->legendre(3);
Returns the value of the Legendre symbol ($x/$y). The value is defined only when $y is an odd prime; when the value is not defined, this currently returns 0 (but that may change in the future, so stay ready).
๐ฆ jacobi
my $x = Math::GMP->new(6);
my $jacobi_verdict = $x->jacobi(3);
Returns the value of the Jacobi symbol ($x/$y). The value is defined only when $y is odd; when the value is not defined, this currently returns 0 (but that may change in the future).
๐ฆ fibonacci
my $fib = Math::GMP::fibonacci(16);
Calculates the n'th number in the Fibonacci sequence. ๐โจ
๐ฆ probab_prime
my $x = Math::GMP->new(7);
my $is_prime_verdict = $x->probab_prime(10);
Probabilistically determines if the number is a prime. The argument is the number of checks to perform. Returns 0 if the number is definitely not a prime, 1 if it may be, and 2 if it definitely is a prime. Vibe check, but for primality ๐
๐ฆ $x->add_ui_gmp($n)
Adds to $x and mutates it in-place. $n must be a regular non-GMP, positive, integer.
๐ฆ ($quotient, $remainder) = $x->bdiv($y);
my $x = Math::GMP->new(7);
my ($quo, $rem) = $x->bdiv(3);
Returns both the division and the modulo of an integer division operation. Two for one, we love to see it.
๐ฆ my $ret = $x->div_2exp_gmp($n);
my $x = Math::GMP->new(200);
my $ret = $x->div_2exp_gmp(2);
Returns a right-shift of the Math::GMP object by an unsigned regular integer. Also look at blshift() .
๐ฆ my $str = $x->get_str_gmp($base)
my $init_n = 3 * 7 + 2 * 7 * 7 + 6 * 7 * 7 * 7;
my $x = Math::GMP->new($init_n);
my $ret = $x->get_str_gmp(7);
print $ret; # Prints "6230".
Returns a string representation of the number in base $base.
๐ฆ my $clone = $x->gmp_copy()
Returns a copy of $x that you can modify without affecting the original. Cloning, but make it math ๐งฌ
๐ฆ my $verdict = $x->gmp_tstbit($bit_index);
Returns whether or not bit No. $bit_index is 1 in $x.
๐ฆ my $remainder = $dividend->mmod_gmp($divisor)
my $x = Math::GMP->new(2 . ('0' x 200) . 4);
my $y = Math::GMP->new(5);
my $ret = $x->mmod_gmp($y);
# $ret is now Math::GMP of 4.
From the GMP documentation:
Divide dividend and divisor and put the remainder in remainder. The remainder is always positive, and its value is less than the value of the divisor.
๐ฆ my $result = $x->mod_2exp_gmp($shift);
my $x = Math::GMP->new(0b10001011);
my $ret = $x->mod_2exp_gmp(4);
# $ret is now Math::GMP of 0b1011
Returns a Math::GMP object containing the lower $shift bits of $x (while not modifying $x).
๐ฆ my $left_shifted = $x->mul_2exp_gmp($shift);
my $x = Math::GMP->new(0b10001011);
my $ret = $x->mul_2exp_gmp(4);
# $ret is now Math::GMP of 0b1000_1011_0000
Returns a Math::GMP object containing $x shifted by $shift bits (where $shift is a plain integer).
๐ฆ my $multiplied = $x->bmulf($float)
my $x = Math::GMP->new(3)->bpow(100);
my $ret = $x->bmulf(1.5);
# $ret is now Math::GMP of floor(3^101 / 2)
Returns a Math::GMP object representing $x multiplied by the floating point value $float (with the result truncated towards zero).
( Added in version 2.23 .)
๐ฆ my $ret = $base->powm_gmp($exp, $mod);
my $base = Math::GMP->new(157);
my $exp = Math::GMP->new(100);
my $mod = Math::GMP->new(5013);
my $ret = $base->powm_gmp($exp, $mod);
# $ret is now (($base ** $exp) % $mod)
Returns $base raised to the power of $exp modulo $mod. ๐ฅ
๐ฆ my $plain_int_ret = $x->sizeinbase_gmp($plain_int_base);
Returns the size of $x in base $plain_int_base .
๐ฆ my $int = $x->intify();
Returns the value of the object as an unblessed (and limited-in-precision) integer. Note the limited precision, bestie โ don't come crying to me.
๐ฆ _gmp_build_version()
my $gmp_version = Math::GMP::_gmp_build_version;
if ($gmp_version ge 6.0.0) {
print "Math::GMP was built against libgmp-6.0.0 or later";
}
Class method that returns as a vstring the version of libgmp against which this module was built.
๐ฆ _gmp_lib_version()
my $gmp_version = Math::GMP::_gmp_lib_version;
if ($gmp_version ge 6.0.0) {
print "Math::GMP is now running with libgmp-6.0.0 or later";
}
Class method that returns as a vstring the version of libgmp it is currently running.
๐ฆ gcd()
An alias to bgcd() .
๐ฆ lcm()
An alias to blcm() .
๐ The internal-only zone โ DO NOT TOUCH ๐
Every single one of these is For internal use. Do not use directly. No cap, just don't.
constantโ For internal use. Do not use directly.destroyโ For internal use. Do not use directly.new_from_scalarโ For internal use. Do not use directly.new_from_scalar_with_baseโ For internal use. Do not use directly.op_addโ For internal use. Do not use directly.op_boolโ For internal use. Do not use directly.op_divโ For internal use. Do not use directly.op_eqโ For internal use. Do not use directly.op_modโ For internal use. Do not use directly.op_mulโ For internal use. Do not use directly.op_numifyโ For internal use. Do not use directly.op_powโ For internal use. Do not use directly.op_spaceshipโ For internal use. Do not use directly.op_stringifyโ For internal use. Do not use directly.op_subโ For internal use. Do not use directly.stringifyโ For internal use. Do not use directly.uintifyโ For internal use. Do not use directly.
okay pausing here, bestie โ that's the end of part 1. There's more of this page coming, so don't close the tab ๐
๐ DIVISION BY ZERO ๐
okay bestie, sit down for this one because it's giving cautionary tale.
so normally perl is like a super protective friend and it catches division by zero for you, handing you a nice lil standard perl-level error message. but libgmp?? libgmp does NOT do that. ๐ the result is usually a SIGFPE (floating point exception), which hands you a core dump if you ever try to divide a Math::GMP object by literally anything that evaluates to zero. and likeโฆ that makes it so hard to figure out where in your perl code the whole thing went off the rails. it's giving "needle in a haystack but the haystack is on fire."
as of perl-5.36.0, SIGFPE is delivered in a way that can actually be caught by a %SIG handler. slay. so you CAN get a stack trace with code like:
use Carp; # load it up front
local $SIG{FPE} = sub { confess(@_) };
but before perl-5.36.0? this approach won't work, bestie. you'll need to use sigaction in POSIX instead:
use Carp;
use POSIX qw{ sigaction SIGFPE };
sigaction(SIGFPE, POSIX::SigAction->new(sub { confess(@_) }));
in either case โ and listen to me on this โ you should not attempt to return from the signal handler, because the signal will just be thrown again. it's persistent like that. ๐
๐ BUGS ๐
as of version 1.0, Math::GMP is mostly compatible with the old Math::BigInt version. it is not a full replacement for the rewritten Math::BigInt versions, though. see the SEE ALSO section on how to achieve using Math::GMP and retain full compatibility to Math::BigInt. iykyk.
there are some slight incompatibilities, such as output of positive numbers not being prefixed by a '+' sign. this is intentional. it's a vibe choice. โจ
there are also some things missing, and not everything might work as expected. (real. noted. moving on.)
๐ VERSION CONTROL ๐
the version control repository of this module is a git repository hosted on GitHub at: <https://github.com/turnstep/Math-GMP>. pull requests are welcome!! come thru, contribute, be the main character. ๐
๐ SEE ALSO ๐
Math::BigInt has a new interface to use a different library than the default pure Perl implementation. you can use, for instance, Math::GMP with it:
use Math::BigInt lib => 'GMP';
if Math::GMP is not installed, it will fall back to its own Perl implementation. no stress, it's got a backup plan.
see Math::BigInt and Math::BigInt::GMP or Math::BigInt::Pari or Math::BigInt::BitVect.
see Math::GMPz, Math::GMPq, and friends ( <https://metacpan.org/search?q=math%3A%3Agmp> ) for bindings of other parts of GMP / MPFR / etc. the friend group is expanding. ๐ซถ
๐ AUTHOR ๐
Chip Turner <chip@redhat.com>, based on the old Math::BigInt by Mark Biggar and Ilya Zakharevich. further extensive work provided by Tels <tels@bloodgate.com>.
Shlomi Fish ( <https://www.shlomifish.org/> ) has done some maintenance work while putting his changes under CC0.
๐ AUTHOR (yes, again, iconic) ๐
Shlomi Fish <shlomif@cpan.org>
ยฉ๏ธ COPYRIGHT AND LICENSE ยฉ๏ธ
this software is Copyright (c) 2000 by James H. Turner.
this is free software, licensed under:
The GNU Lesser General Public License, Version 2.1, February 1999
๐ BUGS (round two, electric boogaloo) ๐
please report any bugs or feature requests on the bugtracker website <https://rt.cpan.org/Public/Dist/Display.html?Name=Math-GMP> or by email to bug-math-gmp@rt.cpan.org <mailto:bug-math-gmp@rt.cpan.org>.
when submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. receipts!! we love receipts. ๐
๐ซ SUPPORT ๐ซ
๐ Perldoc
you can find documentation for this module with the perldoc command.
perldoc Math::GMP
๐ Websites
the following websites have more information about this module, and may be of help to you. as always, in addition to those websites please use your favorite search engine to discover more resources. (google is right there bestie, no judgment)
- MetaCPAN
a modern, open-source CPAN search engine, useful to view POD in HTML format.
<https://metacpan.org/release/Math-GMP>
- RT: CPAN's Bug Tracker
the RT ( Request Tracker ) website is the default bug/issue tracking system for CPAN.
<https://rt.cpan.org/Public/Dist/Display.html?Name=Math-GMP>
- CPANTS
the CPANTS is a website that analyzes the Kwalitee ( code metrics ) of a distribution.
<http://cpants.cpanauthors.org/dist/Math-GMP>
- CPAN Testers
the CPAN Testers is a network of smoke testers who run automated tests on uploaded CPAN distributions.
<http://www.cpantesters.org/distro/M/Math-GMP>
- CPAN Testers Matrix
the CPAN Testers Matrix is a website that provides a visual overview of the test results for a distribution on various Perls/platforms.
<http://matrix.cpantesters.org/?dist=Math-GMP>
- CPAN Testers Dependencies
the CPAN Testers Dependencies is a website that shows a chart of the test results of all dependencies for a distribution.
<http://deps.cpantesters.org/?module=Math::GMP>
๐ Bugs / Feature Requests
please report any bugs or feature requests by email to "bug-math-gmp at rt.cpan.org", or through the web interface at <https://rt.cpan.org/Public/Bug/Report.html?Queue=Math-GMP>. you will be automatically notified of any progress on the request by the system. we'll ping you, don't worry. ๐
๐ป Source Code
the code is open to the world, and available for you to hack on. please feel free to browse it and play with it, or whatever. if you want to contribute patches, please send me a diff or prod me to pull from your repository :) (prodding is 100% an accepted contribution method fr fr)
<https://github.com/turnstep/Math-GMP>
git clone https://github.com/turnstep/Math-GMP.git
okay that's the whole thing, bestie, you made it to the end. ๐ this was Math::GMP(3pm), shipped as part of perl v5.42.3, dated 2026-08-19. go forth, do big number math, and please for the love of everything do not divide by zero. mwah. ๐
โจ๐ธ
๐ฆ where this page comes from
- ubuntu stonking: libmath-gmp-perl 2.25-1build6 ยท LGPL-2.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms