1# GMP perl module 2 3# Copyright 2001-2004 Free Software Foundation, Inc. 4# 5# This file is part of the GNU MP Library. 6# 7# The GNU MP Library is free software; you can redistribute it and/or modify 8# it under the terms of either: 9# 10# * the GNU Lesser General Public License as published by the Free 11# Software Foundation; either version 3 of the License, or (at your 12# option) any later version. 13# 14# or 15# 16# * the GNU General Public License as published by the Free Software 17# Foundation; either version 2 of the License, or (at your option) any 18# later version. 19# 20# or both in parallel, as here. 21# 22# The GNU MP Library is distributed in the hope that it will be useful, but 23# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 24# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 25# for more details. 26# 27# You should have received copies of the GNU General Public License and the 28# GNU Lesser General Public License along with the GNU MP Library. If not, 29# see https://www.gnu.org/licenses/. 30 31# [Note: The above copyright notice is repeated in the documentation section 32# below, in order to get it into man pages etc generated by the various pod 33# conversions. When changing, be sure to update below too.] 34 35 36# This code is designed to work with perl 5.005, so it and the sub-packages 37# aren't as modern as they could be. 38 39package GMP; 40 41require Symbol; 42require Exporter; 43require DynaLoader; 44@ISA = qw(Exporter DynaLoader); 45 46@EXPORT = qw(); 47@EXPORT_OK = qw(version); 48%EXPORT_TAGS = ('all' => [qw( 49 get_d get_d_2exp get_si get_str integer_p 50 printf sgn sprintf)], 51 'constants' => [()]); 52Exporter::export_ok_tags('all'); 53 54$VERSION = '2.00'; 55bootstrap GMP $VERSION; 56 57 58# The format string is cut up into "%" specifiers so GMP types can be 59# passed to GMP::sprintf_internal. Any "*"s are interpolated before 60# calling sprintf_internal, which saves worrying about variable 61# argument lists there. 62# 63# Because sprintf_internal is only called after the conversion and 64# operand have been checked there won't be any crashes from a bad 65# format string. 66# 67sub sprintf { 68 my $fmt = shift; 69 my $out = ''; 70 my ($pre, $dummy, $pat, $rest); 71 72 while (($pre, $dummy, $pat, $rest) = ($fmt =~ /^((%%|[^%])*)(%[- +#.*hlLqv\d]*[bcdfeEgGinopsuxX])(.*)$/s)) { 73 74 $out .= $pre; 75 76 my $pat2 = $pat; # $pat with "*"s expanded 77 my @params = (); # arguments per "*"s 78 while ($pat2 =~ /[*]/) { 79 my $arg = shift; 80 $pat2 =~ s/[*]/$arg/; 81 push @params, $arg; 82 } 83 84 if (UNIVERSAL::isa($_[0],"GMP::Mpz")) { 85 if ($pat2 !~ /[dioxX]$/) { 86 die "GMP::sprintf: unsupported output format for mpz: $pat2\n"; 87 } 88 $pat2 =~ s/(.)$/Z$1/; 89 $out .= sprintf_internal ($pat2, shift); 90 91 } elsif (UNIVERSAL::isa($_[0],"GMP::Mpq")) { 92 if ($pat2 !~ /[dioxX]$/) { 93 die "GMP::sprintf: unsupported output format for mpq: $pat2\n"; 94 } 95 $pat2 =~ s/(.)$/Q$1/; 96 $out .= sprintf_internal ($pat2, shift); 97 98 } elsif (UNIVERSAL::isa($_[0],"GMP::Mpf")) { 99 if ($pat2 !~ /[eEfgG]$/) { 100 die "GMP::sprintf: unsupported output format for mpf: $pat2\n"; 101 } 102 $pat2 =~ s/(.)$/F$1/; 103 $out .= sprintf_internal ($pat2, shift); 104 105 } elsif ($pat =~ /n$/) { 106 # do it this way so h, l or V type modifiers are respected, and use a 107 # dummy variable to avoid a warning about discarding the value 108 my $dummy = sprintf "%s$pat", $out, $_[0]; 109 shift; 110 111 } else { 112 $out .= sprintf $pat, @params, shift; 113 } 114 115 $fmt = $rest; 116 } 117 $out .= $fmt; 118 return $out; 119} 120 121sub printf { 122 if (ref($_[0]) eq 'GLOB') { 123 my $h = Symbol::qualify_to_ref(shift, caller); 124 print $h GMP::sprintf(@_); 125 } else { 126 print STDOUT GMP::sprintf(@_); 127 } 128} 129 1301; 131__END__ 132 133 134 135=head1 NAME 136 137GMP - Perl interface to the GNU Multiple Precision Arithmetic Library 138 139=head1 SYNOPSIS 140 141 use GMP; 142 use GMP::Mpz; 143 use GMP::Mpq; 144 use GMP::Mpf; 145 use GMP::Rand; 146 147=head1 DESCRIPTION 148 149This module provides access to GNU MP arbitrary precision integers, 150rationals and floating point. 151 152No functions are exported from these packages by default, but can be 153selected in the usual way, or the tag :all for everything. 154 155 use GMP::Mpz qw(gcd, lcm); # just these functions 156 use GMP::Mpq qw(:all); # everything in mpq 157 158=head2 GMP::Mpz 159 160This class provides arbitrary precision integers. A new mpz can be 161constructed with C<mpz>. The initial value can be an integer, float, 162string, mpz, mpq or mpf. Floats, mpq and mpf will be automatically 163truncated to an integer. 164 165 use GMP::Mpz qw(:all); 166 my $a = mpz(123); 167 my $b = mpz("0xFFFF"); 168 my $c = mpz(1.5); # truncated 169 170The following overloaded operators are available, and corresponding 171assignment forms like C<+=>, 172 173=over 4 174 175=item 176 177+ - * / % E<lt>E<lt> E<gt>E<gt> ** & | ^ ! E<lt> E<lt>= == != E<gt> E<gt>= 178E<lt>=E<gt> abs not sqrt 179 180=back 181 182C</> and C<%> round towards zero (as per the C<tdiv> functions in GMP). 183 184The following functions are available, behaving the same as the 185corresponding GMP mpz functions, 186 187=over 4 188 189=item 190 191bin, cdiv, cdiv_2exp, clrbit, combit, congruent_p, congruent_2exp_p, 192divexact, divisible_p, divisible_2exp_p, even_p, fac, fdiv, fdiv_2exp, fib, 193fib2, gcd, gcdext, hamdist, invert, jacobi, kronecker, lcm, lucnum, lucnum2, 194mod, mpz_export, mpz_import, nextprime, odd_p, perfect_power_p, 195perfect_square_p, popcount, powm, probab_prime_p, realloc, remove, root, 196roote, scan0, scan1, setbit, sizeinbase, sqrtrem, tdiv, tdiv_2exp, tstbit 197 198=back 199 200C<cdiv>, C<fdiv> and C<tdiv> and their C<2exp> variants return a 201quotient/remainder pair. C<fib2> returns a pair F[n] and F[n-1], similarly 202C<lucnum2>. C<gcd> and C<lcm> accept a variable number of arguments (one or 203more). C<gcdext> returns a triplet of gcd and two cofactors, for example 204 205 use GMP::Mpz qw(:all); 206 $a = 7257; 207 $b = 10701; 208 ($g, $x, $y) = gcdext ($a, $b); 209 print "gcd($a,$b) is $g, and $g == $a*$x + $b*$y\n"; 210 211C<mpz_import> and C<mpz_export> are so named to avoid the C<import> keyword. 212Their parameters are as follows, 213 214 $z = mpz_import ($order, $size, $endian, $nails, $string); 215 $string = mpz_export ($order, $size, $endian, $nails, $z); 216 217The order, size, endian and nails parameters are as per the corresponding C 218functions. The string input for C<mpz_import> is interpreted as byte data 219and must be a multiple of $size bytes. C<mpz_export> conversely returns a 220string of byte data, which will be a multiple of $size bytes. 221 222C<invert> returns the inverse, or undef if it doesn't exist. C<remove> 223returns a remainder/multiplicity pair. C<root> returns the nth root, and 224C<roote> returns a root/bool pair, the bool indicating whether the root is 225exact. C<sqrtrem> and C<rootrem> return a root/remainder pair. 226 227C<clrbit>, C<combit> and C<setbit> expect a variable which they can modify, 228it doesn't make sense to pass a literal constant. Only the given variable 229is modified, if other variables are referencing the same mpz object then a 230new copy is made of it. If the variable isn't an mpz it will be coerced to 231one. For instance, 232 233 use GMP::Mpz qw(setbit); 234 setbit (123, 0); # wrong, don't pass a constant 235 $a = mpz(6); 236 $b = $a; 237 setbit ($a, 0); # $a becomes 7, $b stays at 6 238 239C<scan0> and C<scan1> return ~0 if no 0 or 1 bit respectively is found. 240 241=head2 GMP::Mpq 242 243This class provides rationals with arbitrary precision numerators and 244denominators. A new mpq can be constructed with C<mpq>. The initial value 245can be an integer, float, string, mpz, mpq or mpf, or a pair of integers or 246mpz's. No precision is lost when converting a float or mpf, the exact value 247is retained. 248 249 use GMP::Mpq qw(:all); 250 $a = mpq(); # zero 251 $b = mpq(0.5); # gives 1/2 252 $b = mpq(14); # integer 14 253 $b = mpq(3,4); # fraction 3/4 254 $b = mpq("7/12"); # fraction 7/12 255 $b = mpq("0xFF/0x100"); # fraction 255/256 256 257When a fraction is given, it should be in the canonical form specified in 258the GMP manual, which is denominator positive, no common factors, and zero 259always represented as 0/1. If not then C<canonicalize> can be called to put 260it in that form. For example, 261 262 use GMP::Mpq qw(:all); 263 $q = mpq(21,15); # eek! common factor 3 264 canonicalize($q); # get rid of it 265 266The following overloaded operators are available, and corresponding 267assignment forms like C<+=>, 268 269=over 4 270 271=item 272 273+ - * / E<lt>E<lt> E<gt>E<gt> ** ! E<lt> E<lt>= == != E<gt> E<gt>= 274E<lt>=E<gt> abs not 275 276=back 277 278The following functions are available, 279 280=over 4 281 282=item 283 284den, inv, num 285 286=back 287 288C<inv> calculates 1/q, as per the corresponding GMP function. C<num> and 289C<den> return an mpz copy of the numerator or denominator respectively. In 290the future C<num> and C<den> might give lvalues so the original mpq can be 291modified through them, but this is not done currently. 292 293=head2 GMP::Mpf 294 295This class provides arbitrary precision floating point numbers. The 296mantissa is an arbitrary user-selected precision and the exponent is a fixed 297size (one machine word). 298 299A new mpf can be constructed with C<mpf>. The initial value can be an 300integer, float, string, mpz, mpq or mpf. The second argument specifies the 301desired precision in bits, or if omitted then the default precision is used. 302 303 use GMP::Mpf qw(:all); 304 $a = mpf(); # zero 305 $b = mpf(-7.5); # default precision 306 $c = mpf(1.5, 500); # 500 bits precision 307 $d = mpf("1.0000000000000001"); 308 309The following overloaded operators are available, with the corresponding 310assignment forms like C<+=>, 311 312=over 4 313 314=item 315 316+ - * / E<lt>E<lt> E<gt>E<gt> ** ! E<lt> E<lt>= == != E<gt> E<gt>= 317E<lt>=E<gt> abs not sqrt 318 319=back 320 321The following functions are available, behaving the same as the 322corresponding GMP mpf functions, 323 324=over 4 325 326=item 327 328ceil, floor, get_default_prec, get_prec, mpf_eq, set_default_prec, set_prec, 329trunc 330 331=back 332 333C<mpf_eq> is so named to avoid clashing with the perl C<eq> operator. 334 335C<set_prec> expects a variable which it can modify, it doesn't make sense to 336pass a literal constant. Only the given variable is modified, if other 337variables are referencing the same mpf object then a new copy is made of it. 338If the variable isn't an mpf it will be coerced to one. 339 340Results are the same precision as inputs, or if two mpf's are given to a 341binary operator then the precision of the first is used. For example, 342 343 use GMP::Mpf qw(mpf); 344 $a = mpf(2.0, 100); 345 $b = mpf(2.0, 500); 346 $c = $a + $b; # gives 100 bits precision 347 348Mpf to string conversion via "" or the usual string contexts uses C<$#> the 349same as normal float to string conversions, or defaults to C<%.g> if C<$#> 350is not defined. C<%.g> means all significant digits in the selected 351precision. 352 353=head2 GMP class 354 355The following functions are available in the GMP class, 356 357=over 4 358 359=item 360 361fits_slong_p, get_d, get_d_2exp, get_si, get_str, integer_p, printf, sgn, 362sprintf, version 363 364=back 365 366C<get_d_2exp> accepts any integer, string, float, mpz, mpq or mpf operands 367and returns a float and an integer exponent, 368 369 ($dbl, $exp) = get_d_2exp (mpf ("3.0")); 370 # dbl is 0.75, exp is 2 371 372C<get_str> takes an optional second argument which is the base, defaulting 373to decimal. A negative base means upper case, as per the C functions. For 374integer, integer string, mpz or mpq operands a string is returned. 375 376 use GMP qw(:all); 377 use GMP::Mpq qw(:all); 378 print get_str(mpq(-5,8)),"\n"; # -5/8 379 print get_str(255,16),"\n"; # ff 380 381For float, float strings or mpf operands, C<get_str> accepts an optional 382third parameter being how many digits to produce, defaulting to 0 which 383means all digits. (Only as many digits as can be accurately represented by 384the float precision are ever produced though.) A string/exponent pair is 385returned, as per the C mpf_get_str function. For example, 386 387 use GMP qw(:all); 388 use GMP::Mpf qw(:all); 389 ($s, $e) = get_str(111.111111111, 10, 4); 390 printf ".$se$e\n"; # .1111e3 391 ($s, $e) = get_str(1.625, 10); 392 print "0.$s*10^$e\n"; # 0.1625*10^1 393 ($s, $e) = get_str(mpf(2)**20, 16); 394 printf ".%s@%x\n", $s, $e; # .1@14 395 396C<printf> and C<sprintf> allow formatted output of GMP types. mpz and mpq 397values can be used with integer conversions (d, o, x, X) and mpf with float 398conversions (f, e, E, g, G). All the standard perl printf features are 399available too. For example, 400 401 use GMP::Mpz qw(mpz); 402 use GMP::Mpf qw(mpf); 403 GMP::printf ("%d %d %s", 123, mpz(2)**128, 'foo'); 404 GMP::printf STDERR "%.40f", mpf(1.234); 405 406In perl 5.6.1 it doesn't seem to work to export C<printf>, the plain builtin 407C<printf> is reached unless calls are C<&printf()> style. Explicit use of 408C<GMP::printf> is suggested. C<sprintf> doesn't suffer this problem. 409 410 use GMP qw(sprintf); 411 use GMP::Mpq qw(mpq); 412 $s = sprintf "%x", mpq(15,16); 413 414C<version> is not exported by default or by tag :all, calling it as 415C<GMP::version()> is recommended. It returns the GMP library version 416string, which is not to be confused with the module version number. 417 418The other GMP module functions behave as per the corresponding GMP routines, 419and accept any integer, string, float, mpz, mpq or mpf. For example, 420 421 use GMP qw(:all); 422 use GMP::Mpz qw(mpz); 423 $z = mpz(123); 424 print sgn($z); # gives 1 425 426Because each of GMP::Mpz, GMP::Mpq and GMP::Mpf is a sub-class of GMP, 427C<-E<gt>> style calls work too. 428 429 use GMP qw(:all); 430 use GMP::Mpq qw(mpf); 431 $q = mpq(-5,7); 432 if ($q->integer_p()) # false 433 ... 434 435=head2 GMP::Rand 436 437This class provides objects holding an algorithm and state for random number 438generation. C<randstate> creates a new object, for example, 439 440 use GMP::Rand qw(randstate); 441 $r = randstate(); 442 $r = randstate('lc_2exp_size', 64); 443 $r = randstate('lc_2exp', 43840821, 1, 32); 444 $r = randstate('mt'); 445 $r = randstate($another_r); 446 447With no parameters this corresponds to the C function 448C<gmp_randinit_default>, and is a compromise between speed and randomness. 449'lc_2exp_size' corresponds to C<gmp_randinit_lc_2exp_size>, 'lc_2exp' 450corresponds to C<gmp_randinit_lc_2exp>, and 'mt' corresponds to 451C<gmp_randinit_mt>. Or when passed another randstate object, a copy of that 452object is made. 453 454'lc_2exp_size' can fail if the requested size is bigger than the internal 455table provides for, in which case undef is returned. The maximum size 456currently supported is 128. The other forms always succeed. 457 458A randstate can be seeded with an integer or mpz, using the C<seed> method. 459/dev/random might be a good source of randomness, or time() or 460Time::HiRes::time() might be adequate, depending on the application. 461 462 $r->seed(time())); 463 464Random numbers can be generated with the following functions, 465 466=over 4 467 468=item 469 470mpf_urandomb, mpz_rrandomb, mpz_urandomb, mpz_urandomm, 471gmp_urandomb_ui, gmp_urandomm_ui 472 473=back 474 475Each constructs a new mpz or mpf and with a distribution per the 476corresponding GMP function. For example, 477 478 use GMP::Rand (:all); 479 $r = randstate(); 480 $a = mpz_urandomb($r,256); # uniform mpz, 256 bits 481 $b = mpz_urandomm($r,mpz(3)**100); # uniform mpz, 0 to 3**100-1 482 $c = mpz_rrandomb($r,1024); # special mpz, 1024 bits 483 $f = mpf_urandomb($r,128); # uniform mpf, 128 bits, 0<=$f<1 484 $f = gmp_urandomm_ui($r,56); # uniform int, 0 to 55 485 486=head2 Coercion 487 488Arguments to operators and functions are converted as necessary to the 489appropriate type. For instance C<**> requires an unsigned integer exponent, 490and an mpq argument will be converted, so long as it's an integer in the 491appropriate range. 492 493 use GMP::Mpz (mpz); 494 use GMP::Mpq (mpq); 495 $p = mpz(3) ** mpq(45); # allowed, 45 is an integer 496 497It's an error if a conversion to an integer or mpz would cause any 498truncation. For example, 499 500 use GMP::Mpz (mpz); 501 $p = mpz(3) + 1.25; # not allowed 502 $p = mpz(3) + mpz(1.25); # allowed, explicit truncation 503 504Comparisons, however, accept any combination of operands and are always done 505exactly. For example, 506 507 use GMP::Mpz (mpz); 508 print mpz(3) < 3.1; # true 509 510Variables used on the left of an assignment operator like C<+=> are subject 511to coercion too. An integer, float or string will change type when an mpz, 512mpq or mpf is applied to it. For example, 513 514 use GMP::Mpz (mpz); 515 $a = 1; 516 $a += mpz(1234); # $a becomes an mpz 517 518=head2 Overloading 519 520The rule for binary operators in the C<overload> mechanism is that if both 521operands are class objects then the method from the first is used. This 522determines the result type when mixing GMP classes. For example, 523 524 use GMP::Mpz (mpz); 525 use GMP::Mpq (mpq); 526 use GMP::Mpf (mpf); 527 $z = mpz(123); 528 $q = mpq(3,2); 529 $f = mpf(1.375) 530 print $q+$f; # gives an mpq 531 print $f+$z; # gives an mpf 532 print $z+$f; # not allowed, would lose precision 533 534=head2 Constants 535 536A special tag C<:constants> is recognised in the module exports list. It 537doesn't select any functions, but indicates that perl constants should be 538GMP objects. This can only be used on one of GMP::Mpz, GMP::Mpq or GMP::Mpf 539at any one time, since they apply different rules. 540 541GMP::Mpz will treat constants as mpz's if they're integers, or ordinary 542floats if not. For example, 543 544 use GMP::Mpz qw(:constants); 545 print 764861287634126387126378128,"\n"; # an mpz 546 print 1.25,"\n"; # a float 547 548GMP::Mpq is similar, treating integers as mpq's and leaving floats to the 549normal perl handling. Something like 3/4 is read as two integer mpq's and a 550division, but that's fine since it gives the intended fraction. 551 552 use GMP::Mpq qw(:constants); 553 print 3/4,"\n"; # an mpq 554 print 1.25,"\n"; # a float 555 556GMP::Mpf will treat all constants as mpf's using the default precision. 557BEGIN blocks can be used to set that precision while the code is parsed. 558For example, 559 560 use GMP::Mpf qw(:constants); 561 BEGIN { GMP::Mpf::set_default_prec(256); } 562 print 1/3; 563 BEGIN { GMP::Mpf::set_default_prec(64); } 564 print 5/7; 565 566A similar special tag :noconstants is recognised to turn off the constants 567feature. For example, 568 569 use GMP::Mpz qw(:constants); 570 print 438249738748174928193,"\n"; # an mpz 571 use GMP::Mpz qw(:noconstants); 572 print 438249738748174928193,"\n"; # now a float 573 574All three 'integer', 'binary' and 'float' constant methods are captured. 575'float' is captured even for GMP::Mpz and GMP::Mpq since perl by default 576treats integer strings as floats if they don't fit a plain integer. 577 578=head1 SEE ALSO 579 580GMP manual, L<perl>, L<overload>. 581 582=head1 BUGS 583 584In perl 5.005_03 on i386 FreeBSD, the overloaded constants sometimes provoke 585seg faults. Don't know if that's a perl bug or a GMP module bug, though it 586does seem to go bad before reaching anything in GMP.xs. 587 588There's no way to specify an arbitrary base when converting a string to an 589mpz (or mpq or mpf), only hex or octal with 0x or 0 (for mpz and mpq, but 590not for mpf). 591 592These modules are not reentrant or thread safe, due to the implementation of 593the XSUBs. 594 595Returning a new object from the various functions is convenient, but 596assignment versions could avoid creating new objects. Perhaps they could be 597named after the C language functions, eg. mpq_inv($q,$q); 598 599It'd be good if C<num> and C<den> gave lvalues so the underlying mpq could 600be manipulated. 601 602C<printf> could usefully accept %b for mpz, mpq and mpf, and perhaps %x for 603mpf too. 604 605C<get_str> returning different style values for integer versus float is a 606bit unfortunate. With mpz, mpq and mpf objects there's no doubt what it 607will do, but on a plain scalar its action depends on whether the scalar was 608promoted to a float at any stage, and then on the GMP module rules about 609using the integer or float part. 610 611=head1 INTERNALS 612 613In usual perl object style, an mpz is a reference to an object blessed into 614class C<GMP::Mpz>. The object holds a pointer to the C language C<mpz_t> 615structure. Similarly for mpq, mpf and randstate. 616 617A free list of mpz and mpq values is kept to avoid repeated initializing and 618clearing when objects are created and destroyed. This aims to help speed, 619but it's not clear whether it's really needed. 620 621mpf doesn't use a free list because the precision of new objects can be 622different each time. 623 624No interface to C<mpf_set_prec_raw> is provided. It wouldn't be very useful 625since there's no way to make an operation store its result in a particular 626object. The plain C<set_prec> is useful though, for truncating to a lower 627precision, or as a sort of directive that subsequent calculations involving 628that variable should use a higher precision. 629 630The overheads of perl dynamic typing (operator dispatch, operand type 631checking or coercion) will mean this interface is slower than using C 632directly. 633 634Some assertion checking is available as a compile-time option. 635 636=head1 COPYRIGHT 637 638Copyright 2001-2004 Free Software Foundation, Inc. 639 640This file is part of the GNU MP Library. 641 642The GNU MP Library is free software; you can redistribute it and/or modify 643it under the terms of either: 644 645 * the GNU Lesser General Public License as published by the Free 646 Software Foundation; either version 3 of the License, or (at your 647 option) any later version. 648 649or 650 651 * the GNU General Public License as published by the Free Software 652 Foundation; either version 2 of the License, or (at your option) any 653 later version. 654 655or both in parallel, as here. 656 657The GNU MP Library is distributed in the hope that it will be useful, but 658WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 659or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 660for more details. 661 662You should have received copies of the GNU General Public License and the 663GNU Lesser General Public License along with the GNU MP Library. If not, 664see https://www.gnu.org/licenses/. 665 666=cut 667 668# Local variables: 669# perl-indent-level: 2 670# fill-column: 76 671# End: 672