1# -*- coding: utf-8-unix -*-
2
3package Math::BigInt;
4
5#
6# "Mike had an infinite amount to do and a negative amount of time in which
7# to do it." - Before and After
8#
9
10# The following hash values are used:
11#   value: unsigned int with actual value (as a Math::BigInt::Calc or similar)
12#   sign : +, -, NaN, +inf, -inf
13#   _a   : accuracy
14#   _p   : precision
15
16# Remember not to take shortcuts ala $xs = $x->{value}; $LIB->foo($xs); since
17# underlying lib might change the reference!
18
19use 5.006001;
20use strict;
21use warnings;
22
23use Carp qw< carp croak >;
24
25our $VERSION = '1.999818';
26
27require Exporter;
28our @ISA = qw(Exporter);
29our @EXPORT_OK = qw(objectify bgcd blcm);
30
31# Inside overload, the first arg is always an object. If the original code had
32# it reversed (like $x = 2 * $y), then the third parameter is true.
33# In some cases (like add, $x = $x + 2 is the same as $x = 2 + $x) this makes
34# no difference, but in some cases it does.
35
36# For overloaded ops with only one argument we simple use $_[0]->copy() to
37# preserve the argument.
38
39# Thus inheritance of overload operators becomes possible and transparent for
40# our subclasses without the need to repeat the entire overload section there.
41
42use overload
43
44  # overload key: with_assign
45
46  '+'     =>      sub { $_[0] -> copy() -> badd($_[1]); },
47
48  '-'     =>      sub { my $c = $_[0] -> copy;
49                        $_[2] ? $c -> bneg() -> badd($_[1])
50                              : $c -> bsub($_[1]); },
51
52  '*'     =>      sub { $_[0] -> copy() -> bmul($_[1]); },
53
54  '/'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bdiv($_[0])
55                              : $_[0] -> copy -> bdiv($_[1]); },
56
57  '%'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bmod($_[0])
58                              : $_[0] -> copy -> bmod($_[1]); },
59
60  '**'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bpow($_[0])
61                              : $_[0] -> copy -> bpow($_[1]); },
62
63  '<<'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> blsft($_[0])
64                              : $_[0] -> copy -> blsft($_[1]); },
65
66  '>>'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> brsft($_[0])
67                              : $_[0] -> copy -> brsft($_[1]); },
68
69  # overload key: assign
70
71  '+='    =>      sub { $_[0]->badd($_[1]); },
72
73  '-='    =>      sub { $_[0]->bsub($_[1]); },
74
75  '*='    =>      sub { $_[0]->bmul($_[1]); },
76
77  '/='    =>      sub { scalar $_[0]->bdiv($_[1]); },
78
79  '%='    =>      sub { $_[0]->bmod($_[1]); },
80
81  '**='   =>      sub { $_[0]->bpow($_[1]); },
82
83  '<<='   =>      sub { $_[0]->blsft($_[1]); },
84
85  '>>='   =>      sub { $_[0]->brsft($_[1]); },
86
87#  'x='    =>      sub { },
88
89#  '.='    =>      sub { },
90
91  # overload key: num_comparison
92
93  '<'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> blt($_[0])
94                              : $_[0] -> blt($_[1]); },
95
96  '<='    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> ble($_[0])
97                              : $_[0] -> ble($_[1]); },
98
99  '>'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bgt($_[0])
100                              : $_[0] -> bgt($_[1]); },
101
102  '>='    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bge($_[0])
103                              : $_[0] -> bge($_[1]); },
104
105  '=='    =>      sub { $_[0] -> beq($_[1]); },
106
107  '!='    =>      sub { $_[0] -> bne($_[1]); },
108
109  # overload key: 3way_comparison
110
111  '<=>'   =>      sub { my $cmp = $_[0] -> bcmp($_[1]);
112                        defined($cmp) && $_[2] ? -$cmp : $cmp; },
113
114  'cmp'   =>      sub { $_[2] ? "$_[1]" cmp $_[0] -> bstr()
115                              : $_[0] -> bstr() cmp "$_[1]"; },
116
117  # overload key: str_comparison
118
119#  'lt'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrlt($_[0])
120#                              : $_[0] -> bstrlt($_[1]); },
121#
122#  'le'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrle($_[0])
123#                              : $_[0] -> bstrle($_[1]); },
124#
125#  'gt'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrgt($_[0])
126#                              : $_[0] -> bstrgt($_[1]); },
127#
128#  'ge'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrge($_[0])
129#                              : $_[0] -> bstrge($_[1]); },
130#
131#  'eq'    =>      sub { $_[0] -> bstreq($_[1]); },
132#
133#  'ne'    =>      sub { $_[0] -> bstrne($_[1]); },
134
135  # overload key: binary
136
137  '&'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> band($_[0])
138                              : $_[0] -> copy -> band($_[1]); },
139
140  '&='    =>      sub { $_[0] -> band($_[1]); },
141
142  '|'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bior($_[0])
143                              : $_[0] -> copy -> bior($_[1]); },
144
145  '|='    =>      sub { $_[0] -> bior($_[1]); },
146
147  '^'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bxor($_[0])
148                              : $_[0] -> copy -> bxor($_[1]); },
149
150  '^='    =>      sub { $_[0] -> bxor($_[1]); },
151
152#  '&.'    =>      sub { },
153
154#  '&.='   =>      sub { },
155
156#  '|.'    =>      sub { },
157
158#  '|.='   =>      sub { },
159
160#  '^.'    =>      sub { },
161
162#  '^.='   =>      sub { },
163
164  # overload key: unary
165
166  'neg'   =>      sub { $_[0] -> copy() -> bneg(); },
167
168#  '!'     =>      sub { },
169
170  '~'     =>      sub { $_[0] -> copy() -> bnot(); },
171
172#  '~.'    =>      sub { },
173
174  # overload key: mutators
175
176  '++'    =>      sub { $_[0] -> binc() },
177
178  '--'    =>      sub { $_[0] -> bdec() },
179
180  # overload key: func
181
182  'atan2' =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> batan2($_[0])
183                              : $_[0] -> copy() -> batan2($_[1]); },
184
185  'cos'   =>      sub { $_[0] -> copy -> bcos(); },
186
187  'sin'   =>      sub { $_[0] -> copy -> bsin(); },
188
189  'exp'   =>      sub { $_[0] -> copy() -> bexp($_[1]); },
190
191  'abs'   =>      sub { $_[0] -> copy() -> babs(); },
192
193  'log'   =>      sub { $_[0] -> copy() -> blog(); },
194
195  'sqrt'  =>      sub { $_[0] -> copy() -> bsqrt(); },
196
197  'int'   =>      sub { $_[0] -> copy() -> bint(); },
198
199  # overload key: conversion
200
201  'bool'  =>      sub { $_[0] -> is_zero() ? '' : 1; },
202
203  '""'    =>      sub { $_[0] -> bstr(); },
204
205  '0+'    =>      sub { $_[0] -> numify(); },
206
207  '='     =>      sub { $_[0]->copy(); },
208
209  ;
210
211##############################################################################
212# global constants, flags and accessory
213
214# These vars are public, but their direct usage is not recommended, use the
215# accessor methods instead
216
217our $round_mode = 'even'; # one of 'even', 'odd', '+inf', '-inf', 'zero', 'trunc' or 'common'
218our $accuracy   = undef;
219our $precision  = undef;
220our $div_scale  = 40;
221our $upgrade    = undef;                    # default is no upgrade
222our $downgrade  = undef;                    # default is no downgrade
223
224# These are internally, and not to be used from the outside at all
225
226our $_trap_nan = 0;                         # are NaNs ok? set w/ config()
227our $_trap_inf = 0;                         # are infs ok? set w/ config()
228
229my $nan = 'NaN';                        # constants for easier life
230
231my $LIB = 'Math::BigInt::Calc';        # module to do the low level math
232                                        # default is Calc.pm
233my $IMPORT = 0;                         # was import() called yet?
234                                        # used to make require work
235my %CALLBACKS;                          # callbacks to notify on lib loads
236
237##############################################################################
238# the old code had $rnd_mode, so we need to support it, too
239
240our $rnd_mode   = 'even';
241
242sub TIESCALAR {
243    my ($class) = @_;
244    bless \$round_mode, $class;
245}
246
247sub FETCH {
248    return $round_mode;
249}
250
251sub STORE {
252    $rnd_mode = $_[0]->round_mode($_[1]);
253}
254
255BEGIN {
256    # tie to enable $rnd_mode to work transparently
257    tie $rnd_mode, 'Math::BigInt';
258
259    # set up some handy alias names
260    *as_int = \&as_number;
261    *is_pos = \&is_positive;
262    *is_neg = \&is_negative;
263}
264
265###############################################################################
266# Configuration methods
267###############################################################################
268
269sub round_mode {
270    no strict 'refs';
271    # make Class->round_mode() work
272    my $self = shift;
273    my $class = ref($self) || $self || __PACKAGE__;
274    if (defined $_[0]) {
275        my $m = shift;
276        if ($m !~ /^(even|odd|\+inf|\-inf|zero|trunc|common)$/) {
277            croak("Unknown round mode '$m'");
278        }
279        return ${"${class}::round_mode"} = $m;
280    }
281    ${"${class}::round_mode"};
282}
283
284sub upgrade {
285    no strict 'refs';
286    # make Class->upgrade() work
287    my $self = shift;
288    my $class = ref($self) || $self || __PACKAGE__;
289    # need to set new value?
290    if (@_ > 0) {
291        return ${"${class}::upgrade"} = $_[0];
292    }
293    ${"${class}::upgrade"};
294}
295
296sub downgrade {
297    no strict 'refs';
298    # make Class->downgrade() work
299    my $self = shift;
300    my $class = ref($self) || $self || __PACKAGE__;
301    # need to set new value?
302    if (@_ > 0) {
303        return ${"${class}::downgrade"} = $_[0];
304    }
305    ${"${class}::downgrade"};
306}
307
308sub div_scale {
309    no strict 'refs';
310    # make Class->div_scale() work
311    my $self = shift;
312    my $class = ref($self) || $self || __PACKAGE__;
313    if (defined $_[0]) {
314        if ($_[0] < 0) {
315            croak('div_scale must be greater than zero');
316        }
317        ${"${class}::div_scale"} = $_[0];
318    }
319    ${"${class}::div_scale"};
320}
321
322sub accuracy {
323    # $x->accuracy($a);           ref($x) $a
324    # $x->accuracy();             ref($x)
325    # Class->accuracy();          class
326    # Class->accuracy($a);        class $a
327
328    my $x = shift;
329    my $class = ref($x) || $x || __PACKAGE__;
330
331    no strict 'refs';
332    if (@_ > 0) {
333        my $a = shift;
334        if (defined $a) {
335            $a = $a->numify() if ref($a) && $a->can('numify');
336            # also croak on non-numerical
337            if (!$a || $a <= 0) {
338                croak('Argument to accuracy must be greater than zero');
339            }
340            if (int($a) != $a) {
341                croak('Argument to accuracy must be an integer');
342            }
343        }
344
345        if (ref($x)) {
346            # Set instance variable.
347            $x->bround($a) if $a; # not for undef, 0
348            $x->{_a} = $a;        # set/overwrite, even if not rounded
349            delete $x->{_p};      # clear P
350            # Why return class variable here? Fixme!
351            $a = ${"${class}::accuracy"} unless defined $a; # proper return value
352        } else {
353            # Set class variable.
354            ${"${class}::accuracy"} = $a; # set global A
355            ${"${class}::precision"} = undef; # clear global P
356        }
357
358        return $a;              # shortcut
359    }
360
361    # Return instance variable.
362    return $x->{_a} if ref($x) && (defined $x->{_a} || defined $x->{_p});
363
364    # Return class variable.
365    return ${"${class}::accuracy"};
366}
367
368sub precision {
369    # $x->precision($p);          ref($x) $p
370    # $x->precision();            ref($x)
371    # Class->precision();         class
372    # Class->precision($p);       class $p
373
374    my $x = shift;
375    my $class = ref($x) || $x || __PACKAGE__;
376
377    no strict 'refs';
378    if (@_ > 0) {
379        my $p = shift;
380        if (defined $p) {
381            $p = $p->numify() if ref($p) && $p->can('numify');
382            if ($p != int $p) {
383                croak('Argument to precision must be an integer');
384            }
385        }
386
387        if (ref($x)) {
388            # Set instance variable.
389            $x->bfround($p) if $p; # not for undef, 0
390            $x->{_p} = $p;         # set/overwrite, even if not rounded
391            delete $x->{_a};       # clear A
392            # Why return class variable here? Fixme!
393            $p = ${"${class}::precision"} unless defined $p; # proper return value
394        } else {
395            # Set class variable.
396            ${"${class}::precision"} = $p; # set global P
397            ${"${class}::accuracy"} = undef; # clear global A
398        }
399
400        return $p;              # shortcut
401    }
402
403    # Return instance variable.
404    return $x->{_p} if ref($x) && (defined $x->{_a} || defined $x->{_p});
405
406    # Return class variable.
407    return ${"${class}::precision"};
408}
409
410sub config {
411    # return (or set) configuration data.
412    my $class = shift || __PACKAGE__;
413
414    no strict 'refs';
415    if (@_ > 1 || (@_ == 1 && (ref($_[0]) eq 'HASH'))) {
416        # try to set given options as arguments from hash
417
418        my $args = $_[0];
419        if (ref($args) ne 'HASH') {
420            $args = { @_ };
421        }
422        # these values can be "set"
423        my $set_args = {};
424        foreach my $key (qw/
425                               accuracy precision
426                               round_mode div_scale
427                               upgrade downgrade
428                               trap_inf trap_nan
429                           /)
430        {
431            $set_args->{$key} = $args->{$key} if exists $args->{$key};
432            delete $args->{$key};
433        }
434        if (keys %$args > 0) {
435            croak("Illegal key(s) '", join("', '", keys %$args),
436                        "' passed to $class\->config()");
437        }
438        foreach my $key (keys %$set_args) {
439            if ($key =~ /^trap_(inf|nan)\z/) {
440                ${"${class}::_trap_$1"} = ($set_args->{"trap_$1"} ? 1 : 0);
441                next;
442            }
443            # use a call instead of just setting the $variable to check argument
444            $class->$key($set_args->{$key});
445        }
446    }
447
448    # now return actual configuration
449
450    my $cfg = {
451               lib         => $LIB,
452               lib_version => ${"${LIB}::VERSION"},
453               class       => $class,
454               trap_nan    => ${"${class}::_trap_nan"},
455               trap_inf    => ${"${class}::_trap_inf"},
456               version     => ${"${class}::VERSION"},
457              };
458    foreach my $key (qw/
459                           accuracy precision
460                           round_mode div_scale
461                           upgrade downgrade
462                       /)
463    {
464        $cfg->{$key} = ${"${class}::$key"};
465    }
466    if (@_ == 1 && (ref($_[0]) ne 'HASH')) {
467        # calls of the style config('lib') return just this value
468        return $cfg->{$_[0]};
469    }
470    $cfg;
471}
472
473sub _scale_a {
474    # select accuracy parameter based on precedence,
475    # used by bround() and bfround(), may return undef for scale (means no op)
476    my ($x, $scale, $mode) = @_;
477
478    $scale = $x->{_a} unless defined $scale;
479
480    no strict 'refs';
481    my $class = ref($x);
482
483    $scale = ${ $class . '::accuracy' } unless defined $scale;
484    $mode = ${ $class . '::round_mode' } unless defined $mode;
485
486    if (defined $scale) {
487        $scale = $scale->can('numify') ? $scale->numify()
488                                       : "$scale" if ref($scale);
489        $scale = int($scale);
490    }
491
492    ($scale, $mode);
493}
494
495sub _scale_p {
496    # select precision parameter based on precedence,
497    # used by bround() and bfround(), may return undef for scale (means no op)
498    my ($x, $scale, $mode) = @_;
499
500    $scale = $x->{_p} unless defined $scale;
501
502    no strict 'refs';
503    my $class = ref($x);
504
505    $scale = ${ $class . '::precision' } unless defined $scale;
506    $mode = ${ $class . '::round_mode' } unless defined $mode;
507
508    if (defined $scale) {
509        $scale = $scale->can('numify') ? $scale->numify()
510                                       : "$scale" if ref($scale);
511        $scale = int($scale);
512    }
513
514    ($scale, $mode);
515}
516
517###############################################################################
518# Constructor methods
519###############################################################################
520
521sub new {
522    # Create a new Math::BigInt object from a string or another Math::BigInt
523    # object. See hash keys documented at top.
524
525    # The argument could be an object, so avoid ||, && etc. on it. This would
526    # cause costly overloaded code to be called. The only allowed ops are ref()
527    # and defined.
528
529    my $self    = shift;
530    my $selfref = ref $self;
531    my $class   = $selfref || $self;
532
533    # The POD says:
534    #
535    # "Currently, Math::BigInt->new() defaults to 0, while Math::BigInt->new('')
536    # results in 'NaN'. This might change in the future, so use always the
537    # following explicit forms to get a zero or NaN:
538    #     $zero = Math::BigInt->bzero();
539    #     $nan = Math::BigInt->bnan();
540    #
541    # But although this use has been discouraged for more than 10 years, people
542    # apparently still use it, so we still support it.
543
544    return $self->bzero() unless @_;
545
546    my ($wanted, $a, $p, $r) = @_;
547
548    # Always return a new object, so if called as an instance method, copy the
549    # invocand, and if called as a class method, initialize a new object.
550
551    $self = $selfref ? $self -> copy()
552                     : bless {}, $class;
553
554    unless (defined $wanted) {
555        #carp("Use of uninitialized value in new()");
556        return $self->bzero($a, $p, $r);
557    }
558
559    if (ref($wanted) && $wanted->isa($class)) {         # MBI or subclass
560        # Using "$copy = $wanted -> copy()" here fails some tests. Fixme!
561        my $copy = $class -> copy($wanted);
562        if ($selfref) {
563            %$self = %$copy;
564        } else {
565            $self = $copy;
566        }
567        return $self;
568    }
569
570    $class->import() if $IMPORT == 0;           # make require work
571
572    # Shortcut for non-zero scalar integers with no non-zero exponent.
573
574    if (!ref($wanted) &&
575        $wanted =~ / ^
576                     ([+-]?)            # optional sign
577                     ([1-9][0-9]*)      # non-zero significand
578                     (\.0*)?            # ... with optional zero fraction
579                     ([Ee][+-]?0+)?     # optional zero exponent
580                     \z
581                   /x)
582    {
583        my $sgn = $1;
584        my $abs = $2;
585        $self->{sign} = $sgn || '+';
586        $self->{value} = $LIB->_new($abs);
587
588        no strict 'refs';
589        if (defined($a) || defined($p)
590            || defined(${"${class}::precision"})
591            || defined(${"${class}::accuracy"}))
592        {
593            $self->round($a, $p, $r)
594              unless @_ >= 3 && !defined $a && !defined $p;
595        }
596
597        return $self;
598    }
599
600    # Handle Infs.
601
602    if ($wanted =~ /^\s*([+-]?)inf(inity)?\s*\z/i) {
603        my $sgn = $1 || '+';
604        $self->{sign} = $sgn . 'inf';   # set a default sign for bstr()
605        return $class->binf($sgn);
606    }
607
608    # Handle explicit NaNs (not the ones returned due to invalid input).
609
610    if ($wanted =~ /^\s*([+-]?)nan\s*\z/i) {
611        $self = $class -> bnan();
612        $self->round($a, $p, $r) unless @_ >= 3 && !defined $a && !defined $p;
613        return $self;
614    }
615
616    # Handle hexadecimal numbers.
617
618    if ($wanted =~ /^\s*[+-]?0[Xx]/) {
619        $self = $class -> from_hex($wanted);
620        $self->round($a, $p, $r) unless @_ >= 3 && !defined $a && !defined $p;
621        return $self;
622    }
623
624    # Handle binary numbers.
625
626    if ($wanted =~ /^\s*[+-]?0[Bb]/) {
627        $self = $class -> from_bin($wanted);
628        $self->round($a, $p, $r) unless @_ >= 3 && !defined $a && !defined $p;
629        return $self;
630    }
631
632    # Split string into mantissa, exponent, integer, fraction, value, and sign.
633    my ($mis, $miv, $mfv, $es, $ev) = _split($wanted);
634    if (!ref $mis) {
635        if ($_trap_nan) {
636            croak("$wanted is not a number in $class");
637        }
638        $self->{value} = $LIB->_zero();
639        $self->{sign} = $nan;
640        return $self;
641    }
642
643    if (!ref $miv) {
644        # _from_hex or _from_bin
645        $self->{value} = $mis->{value};
646        $self->{sign} = $mis->{sign};
647        return $self;   # throw away $mis
648    }
649
650    # Make integer from mantissa by adjusting exponent, then convert to a
651    # Math::BigInt.
652    $self->{sign} = $$mis;           # store sign
653    $self->{value} = $LIB->_zero(); # for all the NaN cases
654    my $e = int("$$es$$ev");         # exponent (avoid recursion)
655    if ($e > 0) {
656        my $diff = $e - CORE::length($$mfv);
657        if ($diff < 0) {         # Not integer
658            if ($_trap_nan) {
659                croak("$wanted not an integer in $class");
660            }
661            #print "NOI 1\n";
662            return $upgrade->new($wanted, $a, $p, $r) if defined $upgrade;
663            $self->{sign} = $nan;
664        } else {                 # diff >= 0
665            # adjust fraction and add it to value
666            #print "diff > 0 $$miv\n";
667            $$miv = $$miv . ($$mfv . '0' x $diff);
668        }
669    }
670
671    else {
672        if ($$mfv ne '') {       # e <= 0
673            # fraction and negative/zero E => NOI
674            if ($_trap_nan) {
675                croak("$wanted not an integer in $class");
676            }
677            #print "NOI 2 \$\$mfv '$$mfv'\n";
678            return $upgrade->new($wanted, $a, $p, $r) if defined $upgrade;
679            $self->{sign} = $nan;
680        } elsif ($e < 0) {
681            # xE-y, and empty mfv
682            # Split the mantissa at the decimal point. E.g., if
683            # $$miv = 12345 and $e = -2, then $frac = 45 and $$miv = 123.
684
685            my $frac = substr($$miv, $e); # $frac is fraction part
686            substr($$miv, $e) = "";       # $$miv is now integer part
687
688            if ($frac =~ /[^0]/) {
689                if ($_trap_nan) {
690                    croak("$wanted not an integer in $class");
691                }
692                #print "NOI 3\n";
693                return $upgrade->new($wanted, $a, $p, $r) if defined $upgrade;
694                $self->{sign} = $nan;
695            }
696        }
697    }
698
699    unless ($self->{sign} eq $nan) {
700        $self->{sign} = '+' if $$miv eq '0';            # normalize -0 => +0
701        $self->{value} = $LIB->_new($$miv) if $self->{sign} =~ /^[+-]$/;
702    }
703
704    # If any of the globals are set, use them to round, and store them inside
705    # $self. Do not round for new($x, undef, undef) since that is used by MBF
706    # to signal no rounding.
707
708    $self->round($a, $p, $r) unless @_ >= 3 && !defined $a && !defined $p;
709    $self;
710}
711
712# Create a Math::BigInt from a hexadecimal string.
713
714sub from_hex {
715    my $self    = shift;
716    my $selfref = ref $self;
717    my $class   = $selfref || $self;
718
719    # Don't modify constant (read-only) objects.
720
721    return if $selfref && $self->modify('from_hex');
722
723    my $str = shift;
724
725    # If called as a class method, initialize a new object.
726
727    $self = $class -> bzero() unless $selfref;
728
729    if ($str =~ s/
730                     ^
731                     \s*
732                     ( [+-]? )
733                     (0?x)?
734                     (
735                         [0-9a-fA-F]*
736                         ( _ [0-9a-fA-F]+ )*
737                     )
738                     \s*
739                     $
740                 //x)
741    {
742        # Get a "clean" version of the string, i.e., non-emtpy and with no
743        # underscores or invalid characters.
744
745        my $sign = $1;
746        my $chrs = $3;
747        $chrs =~ tr/_//d;
748        $chrs = '0' unless CORE::length $chrs;
749
750        # The library method requires a prefix.
751
752        $self->{value} = $LIB->_from_hex('0x' . $chrs);
753
754        # Place the sign.
755
756        $self->{sign} = $sign eq '-' && ! $LIB->_is_zero($self->{value})
757                          ? '-' : '+';
758
759        return $self;
760    }
761
762    # CORE::hex() parses as much as it can, and ignores any trailing garbage.
763    # For backwards compatibility, we return NaN.
764
765    return $self->bnan();
766}
767
768# Create a Math::BigInt from an octal string.
769
770sub from_oct {
771    my $self    = shift;
772    my $selfref = ref $self;
773    my $class   = $selfref || $self;
774
775    # Don't modify constant (read-only) objects.
776
777    return if $selfref && $self->modify('from_oct');
778
779    my $str = shift;
780
781    # If called as a class method, initialize a new object.
782
783    $self = $class -> bzero() unless $selfref;
784
785    if ($str =~ s/
786                     ^
787                     \s*
788                     ( [+-]? )
789                     (
790                         [0-7]*
791                         ( _ [0-7]+ )*
792                     )
793                     \s*
794                     $
795                 //x)
796    {
797        # Get a "clean" version of the string, i.e., non-emtpy and with no
798        # underscores or invalid characters.
799
800        my $sign = $1;
801        my $chrs = $2;
802        $chrs =~ tr/_//d;
803        $chrs = '0' unless CORE::length $chrs;
804
805        # The library method requires a prefix.
806
807        $self->{value} = $LIB->_from_oct('0' . $chrs);
808
809        # Place the sign.
810
811        $self->{sign} = $sign eq '-' && ! $LIB->_is_zero($self->{value})
812                          ? '-' : '+';
813
814        return $self;
815    }
816
817    # CORE::oct() parses as much as it can, and ignores any trailing garbage.
818    # For backwards compatibility, we return NaN.
819
820    return $self->bnan();
821}
822
823# Create a Math::BigInt from a binary string.
824
825sub from_bin {
826    my $self    = shift;
827    my $selfref = ref $self;
828    my $class   = $selfref || $self;
829
830    # Don't modify constant (read-only) objects.
831
832    return if $selfref && $self->modify('from_bin');
833
834    my $str = shift;
835
836    # If called as a class method, initialize a new object.
837
838    $self = $class -> bzero() unless $selfref;
839
840    if ($str =~ s/
841                     ^
842                     \s*
843                     ( [+-]? )
844                     (0?b)?
845                     (
846                         [01]*
847                         ( _ [01]+ )*
848                     )
849                     \s*
850                     $
851                 //x)
852    {
853        # Get a "clean" version of the string, i.e., non-emtpy and with no
854        # underscores or invalid characters.
855
856        my $sign = $1;
857        my $chrs = $3;
858        $chrs =~ tr/_//d;
859        $chrs = '0' unless CORE::length $chrs;
860
861        # The library method requires a prefix.
862
863        $self->{value} = $LIB->_from_bin('0b' . $chrs);
864
865        # Place the sign.
866
867        $self->{sign} = $sign eq '-' && ! $LIB->_is_zero($self->{value})
868                          ? '-' : '+';
869
870        return $self;
871    }
872
873    # For consistency with from_hex() and from_oct(), we return NaN when the
874    # input is invalid.
875
876    return $self->bnan();
877
878}
879
880# Create a Math::BigInt from a byte string.
881
882sub from_bytes {
883    my $self    = shift;
884    my $selfref = ref $self;
885    my $class   = $selfref || $self;
886
887    # Don't modify constant (read-only) objects.
888
889    return if $selfref && $self->modify('from_bytes');
890
891    croak("from_bytes() requires a newer version of the $LIB library.")
892        unless $LIB->can('_from_bytes');
893
894    my $str = shift;
895
896    # If called as a class method, initialize a new object.
897
898    $self = $class -> bzero() unless $selfref;
899    $self -> {sign}  = '+';
900    $self -> {value} = $LIB -> _from_bytes($str);
901    return $self;
902}
903
904sub from_base {
905    my $self    = shift;
906    my $selfref = ref $self;
907    my $class   = $selfref || $self;
908
909    # Don't modify constant (read-only) objects.
910
911    return if $selfref && $self->modify('from_base');
912
913    my $str = shift;
914
915    my $base = shift;
916    $base = $class->new($base) unless ref($base);
917
918    croak("the base must be a finite integer >= 2")
919      if $base < 2 || ! $base -> is_int();
920
921    # If called as a class method, initialize a new object.
922
923    $self = $class -> bzero() unless $selfref;
924
925    # If no collating sequence is given, pass some of the conversions to
926    # methods optimized for those cases.
927
928    if (! @_) {
929        return $self -> from_bin($str) if $base == 2;
930        return $self -> from_oct($str) if $base == 8;
931        return $self -> from_hex($str) if $base == 16;
932        if ($base == 10) {
933            my $tmp = $class -> new($str);
934            $self -> {value} = $tmp -> {value};
935            $self -> {sign}  = '+';
936        }
937    }
938
939    croak("from_base() requires a newer version of the $LIB library.")
940      unless $LIB->can('_from_base');
941
942    $self -> {sign}  = '+';
943    $self -> {value}
944      = $LIB->_from_base($str, $base -> {value}, @_ ? shift() : ());
945    return $self
946}
947
948sub bzero {
949    # create/assign '+0'
950
951    if (@_ == 0) {
952        #carp("Using bzero() as a function is deprecated;",
953        #           " use bzero() as a method instead");
954        unshift @_, __PACKAGE__;
955    }
956
957    my $self    = shift;
958    my $selfref = ref $self;
959    my $class   = $selfref || $self;
960
961    $self->import() if $IMPORT == 0;            # make require work
962
963    # Don't modify constant (read-only) objects.
964
965    return if $selfref && $self->modify('bzero');
966
967    $self = bless {}, $class unless $selfref;
968
969    $self->{sign} = '+';
970    $self->{value} = $LIB->_zero();
971
972    # If rounding parameters are given as arguments, use them. If no rounding
973    # parameters are given, and if called as a class method initialize the new
974    # instance with the class variables.
975
976    if (@_) {
977        croak "can't specify both accuracy and precision"
978          if @_ >= 2 && defined $_[0] && defined $_[1];
979        $self->{_a} = $_[0];
980        $self->{_p} = $_[1];
981    } else {
982        unless($selfref) {
983            $self->{_a} = $class -> accuracy();
984            $self->{_p} = $class -> precision();
985        }
986    }
987
988    return $self;
989}
990
991sub bone {
992    # Create or assign '+1' (or -1 if given sign '-').
993
994    if (@_ == 0 || (defined($_[0]) && ($_[0] eq '+' || $_[0] eq '-'))) {
995        #carp("Using bone() as a function is deprecated;",
996        #           " use bone() as a method instead");
997        unshift @_, __PACKAGE__;
998    }
999
1000    my $self    = shift;
1001    my $selfref = ref $self;
1002    my $class   = $selfref || $self;
1003
1004    $self->import() if $IMPORT == 0;            # make require work
1005
1006    # Don't modify constant (read-only) objects.
1007
1008    return if $selfref && $self->modify('bone');
1009
1010    my $sign = '+';             # default
1011    if (@_) {
1012        $sign = shift;
1013        $sign = $sign =~ /^\s*-/ ? "-" : "+";
1014    }
1015
1016    $self = bless {}, $class unless $selfref;
1017
1018    $self->{sign}  = $sign;
1019    $self->{value} = $LIB->_one();
1020
1021    # If rounding parameters are given as arguments, use them. If no rounding
1022    # parameters are given, and if called as a class method initialize the new
1023    # instance with the class variables.
1024
1025    if (@_) {
1026        croak "can't specify both accuracy and precision"
1027          if @_ >= 2 && defined $_[0] && defined $_[1];
1028        $self->{_a} = $_[0];
1029        $self->{_p} = $_[1];
1030    } else {
1031        unless($selfref) {
1032            $self->{_a} = $class -> accuracy();
1033            $self->{_p} = $class -> precision();
1034        }
1035    }
1036
1037    return $self;
1038}
1039
1040sub binf {
1041    # create/assign a '+inf' or '-inf'
1042
1043    if (@_ == 0 || (defined($_[0]) && !ref($_[0]) &&
1044                    $_[0] =~ /^\s*[+-](inf(inity)?)?\s*$/))
1045    {
1046        #carp("Using binf() as a function is deprecated;",
1047        #           " use binf() as a method instead");
1048        unshift @_, __PACKAGE__;
1049    }
1050
1051    my $self    = shift;
1052    my $selfref = ref $self;
1053    my $class   = $selfref || $self;
1054
1055    {
1056        no strict 'refs';
1057        if (${"${class}::_trap_inf"}) {
1058            croak("Tried to create +-inf in $class->binf()");
1059        }
1060    }
1061
1062    $self->import() if $IMPORT == 0;            # make require work
1063
1064    # Don't modify constant (read-only) objects.
1065
1066    return if $selfref && $self->modify('binf');
1067
1068    my $sign = shift;
1069    $sign = defined $sign && $sign =~ /^\s*-/ ? "-" : "+";
1070
1071    $self = bless {}, $class unless $selfref;
1072
1073    $self -> {sign}  = $sign . 'inf';
1074    $self -> {value} = $LIB -> _zero();
1075
1076    # If rounding parameters are given as arguments, use them. If no rounding
1077    # parameters are given, and if called as a class method initialize the new
1078    # instance with the class variables.
1079
1080    if (@_) {
1081        croak "can't specify both accuracy and precision"
1082          if @_ >= 2 && defined $_[0] && defined $_[1];
1083        $self->{_a} = $_[0];
1084        $self->{_p} = $_[1];
1085    } else {
1086        unless($selfref) {
1087            $self->{_a} = $class -> accuracy();
1088            $self->{_p} = $class -> precision();
1089        }
1090    }
1091
1092    return $self;
1093}
1094
1095sub bnan {
1096    # create/assign a 'NaN'
1097
1098    if (@_ == 0) {
1099        #carp("Using bnan() as a function is deprecated;",
1100        #           " use bnan() as a method instead");
1101        unshift @_, __PACKAGE__;
1102    }
1103
1104    my $self    = shift;
1105    my $selfref = ref($self);
1106    my $class   = $selfref || $self;
1107
1108    {
1109        no strict 'refs';
1110        if (${"${class}::_trap_nan"}) {
1111            croak("Tried to create NaN in $class->bnan()");
1112        }
1113    }
1114
1115    $self->import() if $IMPORT == 0;            # make require work
1116
1117    # Don't modify constant (read-only) objects.
1118
1119    return if $selfref && $self->modify('bnan');
1120
1121    $self = bless {}, $class unless $selfref;
1122
1123    $self -> {sign}  = $nan;
1124    $self -> {value} = $LIB -> _zero();
1125
1126    return $self;
1127}
1128
1129sub bpi {
1130    # Calculate PI to N digits. Unless upgrading is in effect, returns the
1131    # result truncated to an integer, that is, always returns '3'.
1132    my ($self, $n) = @_;
1133    if (@_ == 1) {
1134        # called like Math::BigInt::bpi(10);
1135        $n = $self;
1136        $self = __PACKAGE__;
1137    }
1138    $self = ref($self) if ref($self);
1139
1140    return $upgrade->new($n) if defined $upgrade;
1141
1142    # hard-wired to "3"
1143    $self->new(3);
1144}
1145
1146sub copy {
1147    my $self    = shift;
1148    my $selfref = ref $self;
1149    my $class   = $selfref || $self;
1150
1151    # If called as a class method, the object to copy is the next argument.
1152
1153    $self = shift() unless $selfref;
1154
1155    my $copy = bless {}, $class;
1156
1157    $copy->{sign}  = $self->{sign};
1158    $copy->{value} = $LIB->_copy($self->{value});
1159    $copy->{_a}    = $self->{_a} if exists $self->{_a};
1160    $copy->{_p}    = $self->{_p} if exists $self->{_p};
1161
1162    return $copy;
1163}
1164
1165sub as_number {
1166    # An object might be asked to return itself as bigint on certain overloaded
1167    # operations. This does exactly this, so that sub classes can simple inherit
1168    # it or override with their own integer conversion routine.
1169    $_[0]->copy();
1170}
1171
1172###############################################################################
1173# Boolean methods
1174###############################################################################
1175
1176sub is_zero {
1177    # return true if arg (BINT or num_str) is zero (array '+', '0')
1178    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
1179
1180    return 0 if $x->{sign} !~ /^\+$/; # -, NaN & +-inf aren't
1181    $LIB->_is_zero($x->{value});
1182}
1183
1184sub is_one {
1185    # return true if arg (BINT or num_str) is +1, or -1 if sign is given
1186    my ($class, $x, $sign) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
1187
1188    $sign = '+' if !defined $sign || $sign ne '-';
1189
1190    return 0 if $x->{sign} ne $sign; # -1 != +1, NaN, +-inf aren't either
1191    $LIB->_is_one($x->{value});
1192}
1193
1194sub is_finite {
1195    my $x = shift;
1196    return $x->{sign} eq '+' || $x->{sign} eq '-';
1197}
1198
1199sub is_inf {
1200    # return true if arg (BINT or num_str) is +-inf
1201    my ($class, $x, $sign) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
1202
1203    if (defined $sign) {
1204        $sign = '[+-]inf' if $sign eq ''; # +- doesn't matter, only that's inf
1205        $sign = "[$1]inf" if $sign =~ /^([+-])(inf)?$/; # extract '+' or '-'
1206        return $x->{sign} =~ /^$sign$/ ? 1 : 0;
1207    }
1208    $x->{sign} =~ /^[+-]inf$/ ? 1 : 0; # only +-inf is infinity
1209}
1210
1211sub is_nan {
1212    # return true if arg (BINT or num_str) is NaN
1213    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
1214
1215    $x->{sign} eq $nan ? 1 : 0;
1216}
1217
1218sub is_positive {
1219    # return true when arg (BINT or num_str) is positive (> 0)
1220    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
1221
1222    return 1 if $x->{sign} eq '+inf'; # +inf is positive
1223
1224    # 0+ is neither positive nor negative
1225    ($x->{sign} eq '+' && !$x->is_zero()) ? 1 : 0;
1226}
1227
1228sub is_negative {
1229    # return true when arg (BINT or num_str) is negative (< 0)
1230    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
1231
1232    $x->{sign} =~ /^-/ ? 1 : 0; # -inf is negative, but NaN is not
1233}
1234
1235sub is_non_negative {
1236    # Return true if argument is non-negative (>= 0).
1237    my ($class, $x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1238
1239    return 1 if $x->{sign} =~ /^\+/;
1240    return 1 if $x -> is_zero();
1241    return 0;
1242}
1243
1244sub is_non_positive {
1245    # Return true if argument is non-positive (<= 0).
1246    my ($class, $x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1247
1248    return 1 if $x->{sign} =~ /^\-/;
1249    return 1 if $x -> is_zero();
1250    return 0;
1251}
1252
1253sub is_odd {
1254    # return true when arg (BINT or num_str) is odd, false for even
1255    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
1256
1257    return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
1258    $LIB->_is_odd($x->{value});
1259}
1260
1261sub is_even {
1262    # return true when arg (BINT or num_str) is even, false for odd
1263    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
1264
1265    return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
1266    $LIB->_is_even($x->{value});
1267}
1268
1269sub is_int {
1270    # return true when arg (BINT or num_str) is an integer
1271    # always true for Math::BigInt, but different for Math::BigFloat objects
1272    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
1273
1274    $x->{sign} =~ /^[+-]$/ ? 1 : 0; # inf/-inf/NaN aren't
1275}
1276
1277###############################################################################
1278# Comparison methods
1279###############################################################################
1280
1281sub bcmp {
1282    # Compares 2 values.  Returns one of undef, <0, =0, >0. (suitable for sort)
1283    # (BINT or num_str, BINT or num_str) return cond_code
1284
1285    # set up parameters
1286    my ($class, $x, $y) = ref($_[0]) && ref($_[0]) eq ref($_[1])
1287                        ? (ref($_[0]), @_)
1288                        : objectify(2, @_);
1289
1290    return $upgrade->bcmp($x, $y) if defined $upgrade &&
1291      ((!$x->isa($class)) || (!$y->isa($class)));
1292
1293    if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/)) {
1294        # handle +-inf and NaN
1295        return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1296        return 0 if $x->{sign} eq $y->{sign} && $x->{sign} =~ /^[+-]inf$/;
1297        return +1 if $x->{sign} eq '+inf';
1298        return -1 if $x->{sign} eq '-inf';
1299        return -1 if $y->{sign} eq '+inf';
1300        return +1;
1301    }
1302    # check sign for speed first
1303    return 1 if $x->{sign} eq '+' && $y->{sign} eq '-'; # does also 0 <=> -y
1304    return -1 if $x->{sign} eq '-' && $y->{sign} eq '+'; # does also -x <=> 0
1305
1306    # have same sign, so compare absolute values.  Don't make tests for zero
1307    # here because it's actually slower than testing in Calc (especially w/ Pari
1308    # et al)
1309
1310    # post-normalized compare for internal use (honors signs)
1311    if ($x->{sign} eq '+') {
1312        # $x and $y both > 0
1313        return $LIB->_acmp($x->{value}, $y->{value});
1314    }
1315
1316    # $x && $y both < 0
1317    $LIB->_acmp($y->{value}, $x->{value}); # swapped acmp (lib returns 0, 1, -1)
1318}
1319
1320sub bacmp {
1321    # Compares 2 values, ignoring their signs.
1322    # Returns one of undef, <0, =0, >0. (suitable for sort)
1323    # (BINT, BINT) return cond_code
1324
1325    # set up parameters
1326    my ($class, $x, $y) = ref($_[0]) && ref($_[0]) eq ref($_[1])
1327                        ? (ref($_[0]), @_)
1328                        : objectify(2, @_);
1329
1330    return $upgrade->bacmp($x, $y) if defined $upgrade &&
1331      ((!$x->isa($class)) || (!$y->isa($class)));
1332
1333    if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/)) {
1334        # handle +-inf and NaN
1335        return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1336        return 0 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} =~ /^[+-]inf$/;
1337        return 1 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} !~ /^[+-]inf$/;
1338        return -1;
1339    }
1340    $LIB->_acmp($x->{value}, $y->{value}); # lib does only 0, 1, -1
1341}
1342
1343sub beq {
1344    my $self    = shift;
1345    my $selfref = ref $self;
1346
1347    croak 'beq() is an instance method, not a class method' unless $selfref;
1348    croak 'Wrong number of arguments for beq()' unless @_ == 1;
1349
1350    my $cmp = $self -> bcmp(shift);
1351    return defined($cmp) && ! $cmp;
1352}
1353
1354sub bne {
1355    my $self    = shift;
1356    my $selfref = ref $self;
1357
1358    croak 'bne() is an instance method, not a class method' unless $selfref;
1359    croak 'Wrong number of arguments for bne()' unless @_ == 1;
1360
1361    my $cmp = $self -> bcmp(shift);
1362    return defined($cmp) && ! $cmp ? '' : 1;
1363}
1364
1365sub blt {
1366    my $self    = shift;
1367    my $selfref = ref $self;
1368
1369    croak 'blt() is an instance method, not a class method' unless $selfref;
1370    croak 'Wrong number of arguments for blt()' unless @_ == 1;
1371
1372    my $cmp = $self -> bcmp(shift);
1373    return defined($cmp) && $cmp < 0;
1374}
1375
1376sub ble {
1377    my $self    = shift;
1378    my $selfref = ref $self;
1379
1380    croak 'ble() is an instance method, not a class method' unless $selfref;
1381    croak 'Wrong number of arguments for ble()' unless @_ == 1;
1382
1383    my $cmp = $self -> bcmp(shift);
1384    return defined($cmp) && $cmp <= 0;
1385}
1386
1387sub bgt {
1388    my $self    = shift;
1389    my $selfref = ref $self;
1390
1391    croak 'bgt() is an instance method, not a class method' unless $selfref;
1392    croak 'Wrong number of arguments for bgt()' unless @_ == 1;
1393
1394    my $cmp = $self -> bcmp(shift);
1395    return defined($cmp) && $cmp > 0;
1396}
1397
1398sub bge {
1399    my $self    = shift;
1400    my $selfref = ref $self;
1401
1402    croak 'bge() is an instance method, not a class method'
1403        unless $selfref;
1404    croak 'Wrong number of arguments for bge()' unless @_ == 1;
1405
1406    my $cmp = $self -> bcmp(shift);
1407    return defined($cmp) && $cmp >= 0;
1408}
1409
1410###############################################################################
1411# Arithmetic methods
1412###############################################################################
1413
1414sub bneg {
1415    # (BINT or num_str) return BINT
1416    # negate number or make a negated number from string
1417    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
1418
1419    return $x if $x->modify('bneg');
1420
1421    # for +0 do not negate (to have always normalized +0). Does nothing for 'NaN'
1422    $x->{sign} =~ tr/+-/-+/ unless ($x->{sign} eq '+' && $LIB->_is_zero($x->{value}));
1423    $x;
1424}
1425
1426sub babs {
1427    # (BINT or num_str) return BINT
1428    # make number absolute, or return absolute BINT from string
1429    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
1430
1431    return $x if $x->modify('babs');
1432    # post-normalized abs for internal use (does nothing for NaN)
1433    $x->{sign} =~ s/^-/+/;
1434    $x;
1435}
1436
1437sub bsgn {
1438    # Signum function.
1439
1440    my $self = shift;
1441
1442    return $self if $self->modify('bsgn');
1443
1444    return $self -> bone("+") if $self -> is_pos();
1445    return $self -> bone("-") if $self -> is_neg();
1446    return $self;               # zero or NaN
1447}
1448
1449sub bnorm {
1450    # (numstr or BINT) return BINT
1451    # Normalize number -- no-op here
1452    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
1453    $x;
1454}
1455
1456sub binc {
1457    # increment arg by one
1458    my ($class, $x, $a, $p, $r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
1459    return $x if $x->modify('binc');
1460
1461    if ($x->{sign} eq '+') {
1462        $x->{value} = $LIB->_inc($x->{value});
1463        return $x->round($a, $p, $r);
1464    } elsif ($x->{sign} eq '-') {
1465        $x->{value} = $LIB->_dec($x->{value});
1466        $x->{sign} = '+' if $LIB->_is_zero($x->{value}); # -1 +1 => -0 => +0
1467        return $x->round($a, $p, $r);
1468    }
1469    # inf, nan handling etc
1470    $x->badd($class->bone(), $a, $p, $r); # badd does round
1471}
1472
1473sub bdec {
1474    # decrement arg by one
1475    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
1476    return $x if $x->modify('bdec');
1477
1478    if ($x->{sign} eq '-') {
1479        # x already < 0
1480        $x->{value} = $LIB->_inc($x->{value});
1481    } else {
1482        return $x->badd($class->bone('-'), @r)
1483          unless $x->{sign} eq '+'; # inf or NaN
1484        # >= 0
1485        if ($LIB->_is_zero($x->{value})) {
1486            # == 0
1487            $x->{value} = $LIB->_one();
1488            $x->{sign} = '-'; # 0 => -1
1489        } else {
1490            # > 0
1491            $x->{value} = $LIB->_dec($x->{value});
1492        }
1493    }
1494    $x->round(@r);
1495}
1496
1497#sub bstrcmp {
1498#    my $self    = shift;
1499#    my $selfref = ref $self;
1500#    my $class   = $selfref || $self;
1501#
1502#    croak 'bstrcmp() is an instance method, not a class method'
1503#        unless $selfref;
1504#    croak 'Wrong number of arguments for bstrcmp()' unless @_ == 1;
1505#
1506#    return $self -> bstr() CORE::cmp shift;
1507#}
1508#
1509#sub bstreq {
1510#    my $self    = shift;
1511#    my $selfref = ref $self;
1512#    my $class   = $selfref || $self;
1513#
1514#    croak 'bstreq() is an instance method, not a class method'
1515#        unless $selfref;
1516#    croak 'Wrong number of arguments for bstreq()' unless @_ == 1;
1517#
1518#    my $cmp = $self -> bstrcmp(shift);
1519#    return defined($cmp) && ! $cmp;
1520#}
1521#
1522#sub bstrne {
1523#    my $self    = shift;
1524#    my $selfref = ref $self;
1525#    my $class   = $selfref || $self;
1526#
1527#    croak 'bstrne() is an instance method, not a class method'
1528#        unless $selfref;
1529#    croak 'Wrong number of arguments for bstrne()' unless @_ == 1;
1530#
1531#    my $cmp = $self -> bstrcmp(shift);
1532#    return defined($cmp) && ! $cmp ? '' : 1;
1533#}
1534#
1535#sub bstrlt {
1536#    my $self    = shift;
1537#    my $selfref = ref $self;
1538#    my $class   = $selfref || $self;
1539#
1540#    croak 'bstrlt() is an instance method, not a class method'
1541#        unless $selfref;
1542#    croak 'Wrong number of arguments for bstrlt()' unless @_ == 1;
1543#
1544#    my $cmp = $self -> bstrcmp(shift);
1545#    return defined($cmp) && $cmp < 0;
1546#}
1547#
1548#sub bstrle {
1549#    my $self    = shift;
1550#    my $selfref = ref $self;
1551#    my $class   = $selfref || $self;
1552#
1553#    croak 'bstrle() is an instance method, not a class method'
1554#        unless $selfref;
1555#    croak 'Wrong number of arguments for bstrle()' unless @_ == 1;
1556#
1557#    my $cmp = $self -> bstrcmp(shift);
1558#    return defined($cmp) && $cmp <= 0;
1559#}
1560#
1561#sub bstrgt {
1562#    my $self    = shift;
1563#    my $selfref = ref $self;
1564#    my $class   = $selfref || $self;
1565#
1566#    croak 'bstrgt() is an instance method, not a class method'
1567#        unless $selfref;
1568#    croak 'Wrong number of arguments for bstrgt()' unless @_ == 1;
1569#
1570#    my $cmp = $self -> bstrcmp(shift);
1571#    return defined($cmp) && $cmp > 0;
1572#}
1573#
1574#sub bstrge {
1575#    my $self    = shift;
1576#    my $selfref = ref $self;
1577#    my $class   = $selfref || $self;
1578#
1579#    croak 'bstrge() is an instance method, not a class method'
1580#        unless $selfref;
1581#    croak 'Wrong number of arguments for bstrge()' unless @_ == 1;
1582#
1583#    my $cmp = $self -> bstrcmp(shift);
1584#    return defined($cmp) && $cmp >= 0;
1585#}
1586
1587sub badd {
1588    # add second arg (BINT or string) to first (BINT) (modifies first)
1589    # return result as BINT
1590
1591    # set up parameters
1592    my ($class, $x, $y, @r) = (ref($_[0]), @_);
1593    # objectify is costly, so avoid it
1594    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
1595        ($class, $x, $y, @r) = objectify(2, @_);
1596    }
1597
1598    return $x if $x->modify('badd');
1599    return $upgrade->badd($upgrade->new($x), $upgrade->new($y), @r) if defined $upgrade &&
1600      ((!$x->isa($class)) || (!$y->isa($class)));
1601
1602    $r[3] = $y;                 # no push!
1603    # inf and NaN handling
1604    if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/) {
1605        # NaN first
1606        return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1607        # inf handling
1608        if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/)) {
1609            # +inf++inf or -inf+-inf => same, rest is NaN
1610            return $x if $x->{sign} eq $y->{sign};
1611            return $x->bnan();
1612        }
1613        # +-inf + something => +inf
1614        # something +-inf => +-inf
1615        $x->{sign} = $y->{sign}, return $x if $y->{sign} =~ /^[+-]inf$/;
1616        return $x;
1617    }
1618
1619    my ($sx, $sy) = ($x->{sign}, $y->{sign});  # get signs
1620
1621    if ($sx eq $sy) {
1622        $x->{value} = $LIB->_add($x->{value}, $y->{value}); # same sign, abs add
1623    } else {
1624        my $a = $LIB->_acmp ($y->{value}, $x->{value}); # absolute compare
1625        if ($a > 0) {
1626            $x->{value} = $LIB->_sub($y->{value}, $x->{value}, 1); # abs sub w/ swap
1627            $x->{sign} = $sy;
1628        } elsif ($a == 0) {
1629            # speedup, if equal, set result to 0
1630            $x->{value} = $LIB->_zero();
1631            $x->{sign} = '+';
1632        } else                  # a < 0
1633        {
1634            $x->{value} = $LIB->_sub($x->{value}, $y->{value}); # abs sub
1635        }
1636    }
1637    $x->round(@r);
1638}
1639
1640sub bsub {
1641    # (BINT or num_str, BINT or num_str) return BINT
1642    # subtract second arg from first, modify first
1643
1644    # set up parameters
1645    my ($class, $x, $y, @r) = (ref($_[0]), @_);
1646
1647    # objectify is costly, so avoid it
1648    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
1649        ($class, $x, $y, @r) = objectify(2, @_);
1650    }
1651
1652    return $x if $x -> modify('bsub');
1653
1654    return $upgrade -> new($x) -> bsub($upgrade -> new($y), @r)
1655      if defined $upgrade && (!$x -> isa($class) || !$y -> isa($class));
1656
1657    return $x -> round(@r) if $y -> is_zero();
1658
1659    # To correctly handle the lone special case $x -> bsub($x), we note the
1660    # sign of $x, then flip the sign from $y, and if the sign of $x did change,
1661    # too, then we caught the special case:
1662
1663    my $xsign = $x -> {sign};
1664    $y -> {sign} =~ tr/+-/-+/;  # does nothing for NaN
1665    if ($xsign ne $x -> {sign}) {
1666        # special case of $x -> bsub($x) results in 0
1667        return $x -> bzero(@r) if $xsign =~ /^[+-]$/;
1668        return $x -> bnan();    # NaN, -inf, +inf
1669    }
1670    $x -> badd($y, @r);         # badd does not leave internal zeros
1671    $y -> {sign} =~ tr/+-/-+/;  # refix $y (does nothing for NaN)
1672    $x;                         # already rounded by badd() or no rounding
1673}
1674
1675sub bmul {
1676    # multiply the first number by the second number
1677    # (BINT or num_str, BINT or num_str) return BINT
1678
1679    # set up parameters
1680    my ($class, $x, $y, @r) = (ref($_[0]), @_);
1681    # objectify is costly, so avoid it
1682    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
1683        ($class, $x, $y, @r) = objectify(2, @_);
1684    }
1685
1686    return $x if $x->modify('bmul');
1687
1688    return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1689
1690    # inf handling
1691    if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/)) {
1692        return $x->bnan() if $x->is_zero() || $y->is_zero();
1693        # result will always be +-inf:
1694        # +inf * +/+inf => +inf, -inf * -/-inf => +inf
1695        # +inf * -/-inf => -inf, -inf * +/+inf => -inf
1696        return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/);
1697        return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/);
1698        return $x->binf('-');
1699    }
1700
1701    return $upgrade->bmul($x, $upgrade->new($y), @r)
1702      if defined $upgrade && !$y->isa($class);
1703
1704    $r[3] = $y;                 # no push here
1705
1706    $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => +
1707
1708    $x->{value} = $LIB->_mul($x->{value}, $y->{value}); # do actual math
1709    $x->{sign} = '+' if $LIB->_is_zero($x->{value});   # no -0
1710
1711    $x->round(@r);
1712}
1713
1714sub bmuladd {
1715    # multiply two numbers and then add the third to the result
1716    # (BINT or num_str, BINT or num_str, BINT or num_str) return BINT
1717
1718    # set up parameters
1719    my ($class, $x, $y, $z, @r) = objectify(3, @_);
1720
1721    return $x if $x->modify('bmuladd');
1722
1723    return $x->bnan() if (($x->{sign} eq $nan) ||
1724                          ($y->{sign} eq $nan) ||
1725                          ($z->{sign} eq $nan));
1726
1727    # inf handling of x and y
1728    if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/)) {
1729        return $x->bnan() if $x->is_zero() || $y->is_zero();
1730        # result will always be +-inf:
1731        # +inf * +/+inf => +inf, -inf * -/-inf => +inf
1732        # +inf * -/-inf => -inf, -inf * +/+inf => -inf
1733        return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/);
1734        return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/);
1735        return $x->binf('-');
1736    }
1737    # inf handling x*y and z
1738    if (($z->{sign} =~ /^[+-]inf$/)) {
1739        # something +-inf => +-inf
1740        $x->{sign} = $z->{sign}, return $x if $z->{sign} =~ /^[+-]inf$/;
1741    }
1742
1743    return $upgrade->bmuladd($x, $upgrade->new($y), $upgrade->new($z), @r)
1744      if defined $upgrade && (!$y->isa($class) || !$z->isa($class) || !$x->isa($class));
1745
1746    # TODO: what if $y and $z have A or P set?
1747    $r[3] = $z;                 # no push here
1748
1749    $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => +
1750
1751    $x->{value} = $LIB->_mul($x->{value}, $y->{value}); # do actual math
1752    $x->{sign} = '+' if $LIB->_is_zero($x->{value});   # no -0
1753
1754    my ($sx, $sz) = ( $x->{sign}, $z->{sign} ); # get signs
1755
1756    if ($sx eq $sz) {
1757        $x->{value} = $LIB->_add($x->{value}, $z->{value}); # same sign, abs add
1758    } else {
1759        my $a = $LIB->_acmp ($z->{value}, $x->{value}); # absolute compare
1760        if ($a > 0) {
1761            $x->{value} = $LIB->_sub($z->{value}, $x->{value}, 1); # abs sub w/ swap
1762            $x->{sign} = $sz;
1763        } elsif ($a == 0) {
1764            # speedup, if equal, set result to 0
1765            $x->{value} = $LIB->_zero();
1766            $x->{sign} = '+';
1767        } else                  # a < 0
1768        {
1769            $x->{value} = $LIB->_sub($x->{value}, $z->{value}); # abs sub
1770        }
1771    }
1772    $x->round(@r);
1773}
1774
1775sub bdiv {
1776    # This does floored division, where the quotient is floored, i.e., rounded
1777    # towards negative infinity. As a consequence, the remainder has the same
1778    # sign as the divisor.
1779
1780    # Set up parameters.
1781    my ($class, $x, $y, @r) = (ref($_[0]), @_);
1782
1783    # objectify() is costly, so avoid it if we can.
1784    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
1785        ($class, $x, $y, @r) = objectify(2, @_);
1786    }
1787
1788    return $x if $x -> modify('bdiv');
1789
1790    my $wantarray = wantarray;          # call only once
1791
1792    # At least one argument is NaN. Return NaN for both quotient and the
1793    # modulo/remainder.
1794
1795    if ($x -> is_nan() || $y -> is_nan()) {
1796        return $wantarray ? ($x -> bnan(), $class -> bnan()) : $x -> bnan();
1797    }
1798
1799    # Divide by zero and modulo zero.
1800    #
1801    # Division: Use the common convention that x / 0 is inf with the same sign
1802    # as x, except when x = 0, where we return NaN. This is also what earlier
1803    # versions did.
1804    #
1805    # Modulo: In modular arithmetic, the congruence relation z = x (mod y)
1806    # means that there is some integer k such that z - x = k y. If y = 0, we
1807    # get z - x = 0 or z = x. This is also what earlier versions did, except
1808    # that 0 % 0 returned NaN.
1809    #
1810    #     inf /    0 =  inf                  inf %    0 =  inf
1811    #       5 /    0 =  inf                    5 %    0 =    5
1812    #       0 /    0 =  NaN                    0 %    0 =    0
1813    #      -5 /    0 = -inf                   -5 %    0 =   -5
1814    #    -inf /    0 = -inf                 -inf %    0 = -inf
1815
1816    if ($y -> is_zero()) {
1817        my $rem;
1818        if ($wantarray) {
1819            $rem = $x -> copy();
1820        }
1821        if ($x -> is_zero()) {
1822            $x -> bnan();
1823        } else {
1824            $x -> binf($x -> {sign});
1825        }
1826        return $wantarray ? ($x, $rem) : $x;
1827    }
1828
1829    # Numerator (dividend) is +/-inf, and denominator is finite and non-zero.
1830    # The divide by zero cases are covered above. In all of the cases listed
1831    # below we return the same as core Perl.
1832    #
1833    #     inf / -inf =  NaN                  inf % -inf =  NaN
1834    #     inf /   -5 = -inf                  inf %   -5 =  NaN
1835    #     inf /    5 =  inf                  inf %    5 =  NaN
1836    #     inf /  inf =  NaN                  inf %  inf =  NaN
1837    #
1838    #    -inf / -inf =  NaN                 -inf % -inf =  NaN
1839    #    -inf /   -5 =  inf                 -inf %   -5 =  NaN
1840    #    -inf /    5 = -inf                 -inf %    5 =  NaN
1841    #    -inf /  inf =  NaN                 -inf %  inf =  NaN
1842
1843    if ($x -> is_inf()) {
1844        my $rem;
1845        $rem = $class -> bnan() if $wantarray;
1846        if ($y -> is_inf()) {
1847            $x -> bnan();
1848        } else {
1849            my $sign = $x -> bcmp(0) == $y -> bcmp(0) ? '+' : '-';
1850            $x -> binf($sign);
1851        }
1852        return $wantarray ? ($x, $rem) : $x;
1853    }
1854
1855    # Denominator (divisor) is +/-inf. The cases when the numerator is +/-inf
1856    # are covered above. In the modulo cases (in the right column) we return
1857    # the same as core Perl, which does floored division, so for consistency we
1858    # also do floored division in the division cases (in the left column).
1859    #
1860    #      -5 /  inf =   -1                   -5 %  inf =  inf
1861    #       0 /  inf =    0                    0 %  inf =    0
1862    #       5 /  inf =    0                    5 %  inf =    5
1863    #
1864    #      -5 / -inf =    0                   -5 % -inf =   -5
1865    #       0 / -inf =    0                    0 % -inf =    0
1866    #       5 / -inf =   -1                    5 % -inf = -inf
1867
1868    if ($y -> is_inf()) {
1869        my $rem;
1870        if ($x -> is_zero() || $x -> bcmp(0) == $y -> bcmp(0)) {
1871            $rem = $x -> copy() if $wantarray;
1872            $x -> bzero();
1873        } else {
1874            $rem = $class -> binf($y -> {sign}) if $wantarray;
1875            $x -> bone('-');
1876        }
1877        return $wantarray ? ($x, $rem) : $x;
1878    }
1879
1880    # At this point, both the numerator and denominator are finite numbers, and
1881    # the denominator (divisor) is non-zero.
1882
1883    return $upgrade -> bdiv($upgrade -> new($x), $upgrade -> new($y), @r)
1884      if defined $upgrade;
1885
1886    $r[3] = $y;                                   # no push!
1887
1888    # Inialize remainder.
1889
1890    my $rem = $class -> bzero();
1891
1892    # Are both operands the same object, i.e., like $x -> bdiv($x)? If so,
1893    # flipping the sign of $y also flips the sign of $x.
1894
1895    my $xsign = $x -> {sign};
1896    my $ysign = $y -> {sign};
1897
1898    $y -> {sign} =~ tr/+-/-+/;            # Flip the sign of $y, and see ...
1899    my $same = $xsign ne $x -> {sign};    # ... if that changed the sign of $x.
1900    $y -> {sign} = $ysign;                # Re-insert the original sign.
1901
1902    if ($same) {
1903        $x -> bone();
1904    } else {
1905        ($x -> {value}, $rem -> {value}) =
1906          $LIB -> _div($x -> {value}, $y -> {value});
1907
1908        if ($LIB -> _is_zero($rem -> {value})) {
1909            if ($xsign eq $ysign || $LIB -> _is_zero($x -> {value})) {
1910                $x -> {sign} = '+';
1911            } else {
1912                $x -> {sign} = '-';
1913            }
1914        } else {
1915            if ($xsign eq $ysign) {
1916                $x -> {sign} = '+';
1917            } else {
1918                if ($xsign eq '+') {
1919                    $x -> badd(1);
1920                } else {
1921                    $x -> bsub(1);
1922                }
1923                $x -> {sign} = '-';
1924            }
1925        }
1926    }
1927
1928    $x -> round(@r);
1929
1930    if ($wantarray) {
1931        unless ($LIB -> _is_zero($rem -> {value})) {
1932            if ($xsign ne $ysign) {
1933                $rem = $y -> copy() -> babs() -> bsub($rem);
1934            }
1935            $rem -> {sign} = $ysign;
1936        }
1937        $rem -> {_a} = $x -> {_a};
1938        $rem -> {_p} = $x -> {_p};
1939        $rem -> round(@r);
1940        return ($x, $rem);
1941    }
1942
1943    return $x;
1944}
1945
1946sub btdiv {
1947    # This does truncated division, where the quotient is truncted, i.e.,
1948    # rounded towards zero.
1949    #
1950    # ($q, $r) = $x -> btdiv($y) returns $q and $r so that $q is int($x / $y)
1951    # and $q * $y + $r = $x.
1952
1953    # Set up parameters
1954    my ($class, $x, $y, @r) = (ref($_[0]), @_);
1955
1956    # objectify is costly, so avoid it if we can.
1957    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
1958        ($class, $x, $y, @r) = objectify(2, @_);
1959    }
1960
1961    return $x if $x -> modify('btdiv');
1962
1963    my $wantarray = wantarray;          # call only once
1964
1965    # At least one argument is NaN. Return NaN for both quotient and the
1966    # modulo/remainder.
1967
1968    if ($x -> is_nan() || $y -> is_nan()) {
1969        return $wantarray ? ($x -> bnan(), $class -> bnan()) : $x -> bnan();
1970    }
1971
1972    # Divide by zero and modulo zero.
1973    #
1974    # Division: Use the common convention that x / 0 is inf with the same sign
1975    # as x, except when x = 0, where we return NaN. This is also what earlier
1976    # versions did.
1977    #
1978    # Modulo: In modular arithmetic, the congruence relation z = x (mod y)
1979    # means that there is some integer k such that z - x = k y. If y = 0, we
1980    # get z - x = 0 or z = x. This is also what earlier versions did, except
1981    # that 0 % 0 returned NaN.
1982    #
1983    #     inf / 0 =  inf                     inf % 0 =  inf
1984    #       5 / 0 =  inf                       5 % 0 =    5
1985    #       0 / 0 =  NaN                       0 % 0 =    0
1986    #      -5 / 0 = -inf                      -5 % 0 =   -5
1987    #    -inf / 0 = -inf                    -inf % 0 = -inf
1988
1989    if ($y -> is_zero()) {
1990        my $rem;
1991        if ($wantarray) {
1992            $rem = $x -> copy();
1993        }
1994        if ($x -> is_zero()) {
1995            $x -> bnan();
1996        } else {
1997            $x -> binf($x -> {sign});
1998        }
1999        return $wantarray ? ($x, $rem) : $x;
2000    }
2001
2002    # Numerator (dividend) is +/-inf, and denominator is finite and non-zero.
2003    # The divide by zero cases are covered above. In all of the cases listed
2004    # below we return the same as core Perl.
2005    #
2006    #     inf / -inf =  NaN                  inf % -inf =  NaN
2007    #     inf /   -5 = -inf                  inf %   -5 =  NaN
2008    #     inf /    5 =  inf                  inf %    5 =  NaN
2009    #     inf /  inf =  NaN                  inf %  inf =  NaN
2010    #
2011    #    -inf / -inf =  NaN                 -inf % -inf =  NaN
2012    #    -inf /   -5 =  inf                 -inf %   -5 =  NaN
2013    #    -inf /    5 = -inf                 -inf %    5 =  NaN
2014    #    -inf /  inf =  NaN                 -inf %  inf =  NaN
2015
2016    if ($x -> is_inf()) {
2017        my $rem;
2018        $rem = $class -> bnan() if $wantarray;
2019        if ($y -> is_inf()) {
2020            $x -> bnan();
2021        } else {
2022            my $sign = $x -> bcmp(0) == $y -> bcmp(0) ? '+' : '-';
2023            $x -> binf($sign);
2024        }
2025        return $wantarray ? ($x, $rem) : $x;
2026    }
2027
2028    # Denominator (divisor) is +/-inf. The cases when the numerator is +/-inf
2029    # are covered above. In the modulo cases (in the right column) we return
2030    # the same as core Perl, which does floored division, so for consistency we
2031    # also do floored division in the division cases (in the left column).
2032    #
2033    #      -5 /  inf =    0                   -5 %  inf =  -5
2034    #       0 /  inf =    0                    0 %  inf =   0
2035    #       5 /  inf =    0                    5 %  inf =   5
2036    #
2037    #      -5 / -inf =    0                   -5 % -inf =  -5
2038    #       0 / -inf =    0                    0 % -inf =   0
2039    #       5 / -inf =    0                    5 % -inf =   5
2040
2041    if ($y -> is_inf()) {
2042        my $rem;
2043        $rem = $x -> copy() if $wantarray;
2044        $x -> bzero();
2045        return $wantarray ? ($x, $rem) : $x;
2046    }
2047
2048    return $upgrade -> btdiv($upgrade -> new($x), $upgrade -> new($y), @r)
2049      if defined $upgrade;
2050
2051    $r[3] = $y;                 # no push!
2052
2053    # Inialize remainder.
2054
2055    my $rem = $class -> bzero();
2056
2057    # Are both operands the same object, i.e., like $x -> bdiv($x)? If so,
2058    # flipping the sign of $y also flips the sign of $x.
2059
2060    my $xsign = $x -> {sign};
2061    my $ysign = $y -> {sign};
2062
2063    $y -> {sign} =~ tr/+-/-+/;            # Flip the sign of $y, and see ...
2064    my $same = $xsign ne $x -> {sign};    # ... if that changed the sign of $x.
2065    $y -> {sign} = $ysign;                # Re-insert the original sign.
2066
2067    if ($same) {
2068        $x -> bone();
2069    } else {
2070        ($x -> {value}, $rem -> {value}) =
2071          $LIB -> _div($x -> {value}, $y -> {value});
2072
2073        $x -> {sign} = $xsign eq $ysign ? '+' : '-';
2074        $x -> {sign} = '+' if $LIB -> _is_zero($x -> {value});
2075        $x -> round(@r);
2076    }
2077
2078    if (wantarray) {
2079        $rem -> {sign} = $xsign;
2080        $rem -> {sign} = '+' if $LIB -> _is_zero($rem -> {value});
2081        $rem -> {_a} = $x -> {_a};
2082        $rem -> {_p} = $x -> {_p};
2083        $rem -> round(@r);
2084        return ($x, $rem);
2085    }
2086
2087    return $x;
2088}
2089
2090sub bmod {
2091    # This is the remainder after floored division.
2092
2093    # Set up parameters.
2094    my ($class, $x, $y, @r) = (ref($_[0]), @_);
2095
2096    # objectify is costly, so avoid it
2097    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
2098        ($class, $x, $y, @r) = objectify(2, @_);
2099    }
2100
2101    return $x if $x -> modify('bmod');
2102    $r[3] = $y;                 # no push!
2103
2104    # At least one argument is NaN.
2105
2106    if ($x -> is_nan() || $y -> is_nan()) {
2107        return $x -> bnan();
2108    }
2109
2110    # Modulo zero. See documentation for bdiv().
2111
2112    if ($y -> is_zero()) {
2113        return $x;
2114    }
2115
2116    # Numerator (dividend) is +/-inf.
2117
2118    if ($x -> is_inf()) {
2119        return $x -> bnan();
2120    }
2121
2122    # Denominator (divisor) is +/-inf.
2123
2124    if ($y -> is_inf()) {
2125        if ($x -> is_zero() || $x -> bcmp(0) == $y -> bcmp(0)) {
2126            return $x;
2127        } else {
2128            return $x -> binf($y -> sign());
2129        }
2130    }
2131
2132    # Calc new sign and in case $y == +/- 1, return $x.
2133
2134    $x -> {value} = $LIB -> _mod($x -> {value}, $y -> {value});
2135    if ($LIB -> _is_zero($x -> {value})) {
2136        $x -> {sign} = '+';     # do not leave -0
2137    } else {
2138        $x -> {value} = $LIB -> _sub($y -> {value}, $x -> {value}, 1) # $y-$x
2139          if ($x -> {sign} ne $y -> {sign});
2140        $x -> {sign} = $y -> {sign};
2141    }
2142
2143    $x -> round(@r);
2144}
2145
2146sub btmod {
2147    # Remainder after truncated division.
2148
2149    # set up parameters
2150    my ($class, $x, $y, @r) = (ref($_[0]), @_);
2151
2152    # objectify is costly, so avoid it
2153    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
2154        ($class, $x, $y, @r) = objectify(2, @_);
2155    }
2156
2157    return $x if $x -> modify('btmod');
2158
2159    # At least one argument is NaN.
2160
2161    if ($x -> is_nan() || $y -> is_nan()) {
2162        return $x -> bnan();
2163    }
2164
2165    # Modulo zero. See documentation for btdiv().
2166
2167    if ($y -> is_zero()) {
2168        return $x;
2169    }
2170
2171    # Numerator (dividend) is +/-inf.
2172
2173    if ($x -> is_inf()) {
2174        return $x -> bnan();
2175    }
2176
2177    # Denominator (divisor) is +/-inf.
2178
2179    if ($y -> is_inf()) {
2180        return $x;
2181    }
2182
2183    return $upgrade -> btmod($upgrade -> new($x), $upgrade -> new($y), @r)
2184      if defined $upgrade;
2185
2186    $r[3] = $y;                 # no push!
2187
2188    my $xsign = $x -> {sign};
2189
2190    $x -> {value} = $LIB -> _mod($x -> {value}, $y -> {value});
2191
2192    $x -> {sign} = $xsign;
2193    $x -> {sign} = '+' if $LIB -> _is_zero($x -> {value});
2194    $x -> round(@r);
2195    return $x;
2196}
2197
2198sub bmodinv {
2199    # Return modular multiplicative inverse:
2200    #
2201    #   z is the modular inverse of x (mod y) if and only if
2202    #
2203    #       x*z ≡ 1  (mod y)
2204    #
2205    # If the modulus y is larger than one, x and z are relative primes (i.e.,
2206    # their greatest common divisor is one).
2207    #
2208    # If no modular multiplicative inverse exists, NaN is returned.
2209
2210    # set up parameters
2211    my ($class, $x, $y, @r) = (undef, @_);
2212    # objectify is costly, so avoid it
2213    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
2214        ($class, $x, $y, @r) = objectify(2, @_);
2215    }
2216
2217    return $x if $x->modify('bmodinv');
2218
2219    # Return NaN if one or both arguments is +inf, -inf, or nan.
2220
2221    return $x->bnan() if ($y->{sign} !~ /^[+-]$/ ||
2222                          $x->{sign} !~ /^[+-]$/);
2223
2224    # Return NaN if $y is zero; 1 % 0 makes no sense.
2225
2226    return $x->bnan() if $y->is_zero();
2227
2228    # Return 0 in the trivial case. $x % 1 or $x % -1 is zero for all finite
2229    # integers $x.
2230
2231    return $x->bzero() if ($y->is_one() ||
2232                           $y->is_one('-'));
2233
2234    # Return NaN if $x = 0, or $x modulo $y is zero. The only valid case when
2235    # $x = 0 is when $y = 1 or $y = -1, but that was covered above.
2236    #
2237    # Note that computing $x modulo $y here affects the value we'll feed to
2238    # $LIB->_modinv() below when $x and $y have opposite signs. E.g., if $x =
2239    # 5 and $y = 7, those two values are fed to _modinv(), but if $x = -5 and
2240    # $y = 7, the values fed to _modinv() are $x = 2 (= -5 % 7) and $y = 7.
2241    # The value if $x is affected only when $x and $y have opposite signs.
2242
2243    $x->bmod($y);
2244    return $x->bnan() if $x->is_zero();
2245
2246    # Compute the modular multiplicative inverse of the absolute values. We'll
2247    # correct for the signs of $x and $y later. Return NaN if no GCD is found.
2248
2249    ($x->{value}, $x->{sign}) = $LIB->_modinv($x->{value}, $y->{value});
2250    return $x->bnan() if !defined $x->{value};
2251
2252    # Library inconsistency workaround: _modinv() in Math::BigInt::GMP versions
2253    # <= 1.32 return undef rather than a "+" for the sign.
2254
2255    $x->{sign} = '+' unless defined $x->{sign};
2256
2257    # When one or both arguments are negative, we have the following
2258    # relations.  If x and y are positive:
2259    #
2260    #   modinv(-x, -y) = -modinv(x, y)
2261    #   modinv(-x, y) = y - modinv(x, y)  = -modinv(x, y) (mod y)
2262    #   modinv( x, -y) = modinv(x, y) - y  =  modinv(x, y) (mod -y)
2263
2264    # We must swap the sign of the result if the original $x is negative.
2265    # However, we must compensate for ignoring the signs when computing the
2266    # inverse modulo. The net effect is that we must swap the sign of the
2267    # result if $y is negative.
2268
2269    $x -> bneg() if $y->{sign} eq '-';
2270
2271    # Compute $x modulo $y again after correcting the sign.
2272
2273    $x -> bmod($y) if $x->{sign} ne $y->{sign};
2274
2275    return $x;
2276}
2277
2278sub bmodpow {
2279    # Modular exponentiation. Raises a very large number to a very large exponent
2280    # in a given very large modulus quickly, thanks to binary exponentiation.
2281    # Supports negative exponents.
2282    my ($class, $num, $exp, $mod, @r) = objectify(3, @_);
2283
2284    return $num if $num->modify('bmodpow');
2285
2286    # When the exponent 'e' is negative, use the following relation, which is
2287    # based on finding the multiplicative inverse 'd' of 'b' modulo 'm':
2288    #
2289    #    b^(-e) (mod m) = d^e (mod m) where b*d = 1 (mod m)
2290
2291    $num->bmodinv($mod) if ($exp->{sign} eq '-');
2292
2293    # Check for valid input. All operands must be finite, and the modulus must be
2294    # non-zero.
2295
2296    return $num->bnan() if ($num->{sign} =~ /NaN|inf/ || # NaN, -inf, +inf
2297                            $exp->{sign} =~ /NaN|inf/ || # NaN, -inf, +inf
2298                            $mod->{sign} =~ /NaN|inf/);  # NaN, -inf, +inf
2299
2300    # Modulo zero. See documentation for Math::BigInt's bmod() method.
2301
2302    if ($mod -> is_zero()) {
2303        if ($num -> is_zero()) {
2304            return $class -> bnan();
2305        } else {
2306            return $num -> copy();
2307        }
2308    }
2309
2310    # Compute 'a (mod m)', ignoring the signs on 'a' and 'm'. If the resulting
2311    # value is zero, the output is also zero, regardless of the signs on 'a' and
2312    # 'm'.
2313
2314    my $value = $LIB->_modpow($num->{value}, $exp->{value}, $mod->{value});
2315    my $sign  = '+';
2316
2317    # If the resulting value is non-zero, we have four special cases, depending
2318    # on the signs on 'a' and 'm'.
2319
2320    unless ($LIB->_is_zero($value)) {
2321
2322        # There is a negative sign on 'a' (= $num**$exp) only if the number we
2323        # are exponentiating ($num) is negative and the exponent ($exp) is odd.
2324
2325        if ($num->{sign} eq '-' && $exp->is_odd()) {
2326
2327            # When both the number 'a' and the modulus 'm' have a negative sign,
2328            # use this relation:
2329            #
2330            #    -a (mod -m) = -(a (mod m))
2331
2332            if ($mod->{sign} eq '-') {
2333                $sign = '-';
2334            }
2335
2336            # When only the number 'a' has a negative sign, use this relation:
2337            #
2338            #    -a (mod m) = m - (a (mod m))
2339
2340            else {
2341                # Use copy of $mod since _sub() modifies the first argument.
2342                my $mod = $LIB->_copy($mod->{value});
2343                $value = $LIB->_sub($mod, $value);
2344                $sign  = '+';
2345            }
2346
2347        } else {
2348
2349            # When only the modulus 'm' has a negative sign, use this relation:
2350            #
2351            #    a (mod -m) = (a (mod m)) - m
2352            #               = -(m - (a (mod m)))
2353
2354            if ($mod->{sign} eq '-') {
2355                # Use copy of $mod since _sub() modifies the first argument.
2356                my $mod = $LIB->_copy($mod->{value});
2357                $value = $LIB->_sub($mod, $value);
2358                $sign  = '-';
2359            }
2360
2361            # When neither the number 'a' nor the modulus 'm' have a negative
2362            # sign, directly return the already computed value.
2363            #
2364            #    (a (mod m))
2365
2366        }
2367
2368    }
2369
2370    $num->{value} = $value;
2371    $num->{sign}  = $sign;
2372
2373    return $num -> round(@r);
2374}
2375
2376sub bpow {
2377    # (BINT or num_str, BINT or num_str) return BINT
2378    # compute power of two numbers -- stolen from Knuth Vol 2 pg 233
2379    # modifies first argument
2380
2381    # set up parameters
2382    my ($class, $x, $y, @r) = (ref($_[0]), @_);
2383    # objectify is costly, so avoid it
2384    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
2385        ($class, $x, $y, @r) = objectify(2, @_);
2386    }
2387
2388    return $x if $x->modify('bpow');
2389
2390    # $x and/or $y is a NaN
2391    return $x->bnan() if $x->is_nan() || $y->is_nan();
2392
2393    # $x and/or $y is a +/-Inf
2394    if ($x->is_inf("-")) {
2395        return $x->bzero()   if $y->is_negative();
2396        return $x->bnan()    if $y->is_zero();
2397        return $x            if $y->is_odd();
2398        return $x->bneg();
2399    } elsif ($x->is_inf("+")) {
2400        return $x->bzero()   if $y->is_negative();
2401        return $x->bnan()    if $y->is_zero();
2402        return $x;
2403    } elsif ($y->is_inf("-")) {
2404        return $x->bnan()    if $x -> is_one("-");
2405        return $x->binf("+") if $x -> is_zero();
2406        return $x->bone()    if $x -> is_one("+");
2407        return $x->bzero();
2408    } elsif ($y->is_inf("+")) {
2409        return $x->bnan()    if $x -> is_one("-");
2410        return $x->bzero()   if $x -> is_zero();
2411        return $x->bone()    if $x -> is_one("+");
2412        return $x->binf("+");
2413    }
2414
2415    return $upgrade->bpow($upgrade->new($x), $y, @r)
2416      if defined $upgrade && (!$y->isa($class) || $y->{sign} eq '-');
2417
2418    $r[3] = $y;                 # no push!
2419
2420    # 0 ** -y => ( 1 / (0 ** y)) => 1 / 0 => +inf
2421    return $x->binf() if $y->is_negative() && $x->is_zero();
2422
2423    # 1 ** -y => 1 / (1 ** |y|)
2424    return $x->bzero() if $y->is_negative() && !$LIB->_is_one($x->{value});
2425
2426    $x->{value} = $LIB->_pow($x->{value}, $y->{value});
2427    $x->{sign}  = $x->is_negative() && $y->is_odd() ? '-' : '+';
2428    $x->round(@r);
2429}
2430
2431sub blog {
2432    # Return the logarithm of the operand. If a second operand is defined, that
2433    # value is used as the base, otherwise the base is assumed to be Euler's
2434    # constant.
2435
2436    my ($class, $x, $base, @r);
2437
2438    # Don't objectify the base, since an undefined base, as in $x->blog() or
2439    # $x->blog(undef) signals that the base is Euler's number.
2440
2441    if (!ref($_[0]) && $_[0] =~ /^[A-Za-z]|::/) {
2442        # E.g., Math::BigInt->blog(256, 2)
2443        ($class, $x, $base, @r) =
2444          defined $_[2] ? objectify(2, @_) : objectify(1, @_);
2445    } else {
2446        # E.g., Math::BigInt::blog(256, 2) or $x->blog(2)
2447        ($class, $x, $base, @r) =
2448          defined $_[1] ? objectify(2, @_) : objectify(1, @_);
2449    }
2450
2451    return $x if $x->modify('blog');
2452
2453    # Handle all exception cases and all trivial cases. I have used Wolfram
2454    # Alpha (http://www.wolframalpha.com) as the reference for these cases.
2455
2456    return $x -> bnan() if $x -> is_nan();
2457
2458    if (defined $base) {
2459        $base = $class -> new($base) unless ref $base;
2460        if ($base -> is_nan() || $base -> is_one()) {
2461            return $x -> bnan();
2462        } elsif ($base -> is_inf() || $base -> is_zero()) {
2463            return $x -> bnan() if $x -> is_inf() || $x -> is_zero();
2464            return $x -> bzero();
2465        } elsif ($base -> is_negative()) {        # -inf < base < 0
2466            return $x -> bzero() if $x -> is_one(); #     x = 1
2467            return $x -> bone()  if $x == $base;    #     x = base
2468            return $x -> bnan();                    #     otherwise
2469        }
2470        return $x -> bone() if $x == $base; # 0 < base && 0 < x < inf
2471    }
2472
2473    # We now know that the base is either undefined or >= 2 and finite.
2474
2475    return $x -> binf('+') if $x -> is_inf(); #   x = +/-inf
2476    return $x -> bnan()    if $x -> is_neg(); #   -inf < x < 0
2477    return $x -> bzero()   if $x -> is_one(); #   x = 1
2478    return $x -> binf('-') if $x -> is_zero(); #   x = 0
2479
2480    # At this point we are done handling all exception cases and trivial cases.
2481
2482    return $upgrade -> blog($upgrade -> new($x), $base, @r) if defined $upgrade;
2483
2484    # fix for bug #24969:
2485    # the default base is e (Euler's number) which is not an integer
2486    if (!defined $base) {
2487        require Math::BigFloat;
2488        my $u = Math::BigFloat->blog(Math::BigFloat->new($x))->as_int();
2489        # modify $x in place
2490        $x->{value} = $u->{value};
2491        $x->{sign} = $u->{sign};
2492        return $x;
2493    }
2494
2495    my ($rc) = $LIB->_log_int($x->{value}, $base->{value});
2496    return $x->bnan() unless defined $rc; # not possible to take log?
2497    $x->{value} = $rc;
2498    $x->round(@r);
2499}
2500
2501sub bexp {
2502    # Calculate e ** $x (Euler's number to the power of X), truncated to
2503    # an integer value.
2504    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
2505    return $x if $x->modify('bexp');
2506
2507    # inf, -inf, NaN, <0 => NaN
2508    return $x->bnan() if $x->{sign} eq 'NaN';
2509    return $x->bone() if $x->is_zero();
2510    return $x if $x->{sign} eq '+inf';
2511    return $x->bzero() if $x->{sign} eq '-inf';
2512
2513    my $u;
2514    {
2515        # run through Math::BigFloat unless told otherwise
2516        require Math::BigFloat unless defined $upgrade;
2517        local $upgrade = 'Math::BigFloat' unless defined $upgrade;
2518        # calculate result, truncate it to integer
2519        $u = $upgrade->bexp($upgrade->new($x), @r);
2520    }
2521
2522    if (defined $upgrade) {
2523        $x = $u;
2524    } else {
2525        $u = $u->as_int();
2526        # modify $x in place
2527        $x->{value} = $u->{value};
2528        $x->round(@r);
2529    }
2530}
2531
2532sub bnok {
2533    # Calculate n over k (binomial coefficient or "choose" function) as
2534    # integer.
2535
2536    # Set up parameters.
2537    my ($self, $n, $k, @r) = (ref($_[0]), @_);
2538
2539    # Objectify is costly, so avoid it.
2540    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
2541        ($self, $n, $k, @r) = objectify(2, @_);
2542    }
2543
2544    return $n if $n->modify('bnok');
2545
2546    # All cases where at least one argument is NaN.
2547
2548    return $n->bnan() if $n->{sign} eq 'NaN' || $k->{sign} eq 'NaN';
2549
2550    # All cases where at least one argument is +/-inf.
2551
2552    if ($n -> is_inf()) {
2553        if ($k -> is_inf()) {                   # bnok(+/-inf,+/-inf)
2554            return $n -> bnan();
2555        } elsif ($k -> is_neg()) {              # bnok(+/-inf,k), k < 0
2556            return $n -> bzero();
2557        } elsif ($k -> is_zero()) {             # bnok(+/-inf,k), k = 0
2558            return $n -> bone();
2559        } else {
2560            if ($n -> is_inf("+")) {            # bnok(+inf,k), 0 < k < +inf
2561                return $n -> binf("+");
2562            } else {                            # bnok(-inf,k), k > 0
2563                my $sign = $k -> is_even() ? "+" : "-";
2564                return $n -> binf($sign);
2565            }
2566        }
2567    }
2568
2569    elsif ($k -> is_inf()) {            # bnok(n,+/-inf), -inf <= n <= inf
2570        return $n -> bnan();
2571    }
2572
2573    # At this point, both n and k are real numbers.
2574
2575    my $sign = 1;
2576
2577    if ($n >= 0) {
2578        if ($k < 0 || $k > $n) {
2579            return $n -> bzero();
2580        }
2581    } else {
2582
2583        if ($k >= 0) {
2584
2585            # n < 0 and k >= 0: bnok(n,k) = (-1)^k * bnok(-n+k-1,k)
2586
2587            $sign = (-1) ** $k;
2588            $n -> bneg() -> badd($k) -> bdec();
2589
2590        } elsif ($k <= $n) {
2591
2592            # n < 0 and k <= n: bnok(n,k) = (-1)^(n-k) * bnok(-k-1,n-k)
2593
2594            $sign = (-1) ** ($n - $k);
2595            my $x0 = $n -> copy();
2596            $n -> bone() -> badd($k) -> bneg();
2597            $k = $k -> copy();
2598            $k -> bneg() -> badd($x0);
2599
2600        } else {
2601
2602            # n < 0 and n < k < 0:
2603
2604            return $n -> bzero();
2605        }
2606    }
2607
2608    $n->{value} = $LIB->_nok($n->{value}, $k->{value});
2609    $n -> bneg() if $sign == -1;
2610
2611    $n->round(@r);
2612}
2613
2614sub buparrow {
2615    my $a = shift;
2616    my $y = $a -> uparrow(@_);
2617    $a -> {value} = $y -> {value};
2618    return $a;
2619}
2620
2621sub uparrow {
2622    # Knuth's up-arrow notation buparrow(a, n, b)
2623    #
2624    # The following is a simple, recursive implementation of the up-arrow
2625    # notation, just to show the idea. Such implementations cause "Deep
2626    # recursion on subroutine ..." warnings, so we use a faster, non-recursive
2627    # algorithm below with @_ as a stack.
2628    #
2629    #   sub buparrow {
2630    #       my ($a, $n, $b) = @_;
2631    #       return $a ** $b if $n == 1;
2632    #       return $a * $b  if $n == 0;
2633    #       return 1        if $b == 0;
2634    #       return buparrow($a, $n - 1, buparrow($a, $n, $b - 1));
2635    #   }
2636
2637    my ($a, $b, $n) = @_;
2638    my $class = ref $a;
2639    croak("a must be non-negative") if $a < 0;
2640    croak("n must be non-negative") if $n < 0;
2641    croak("b must be non-negative") if $b < 0;
2642
2643    while (@_ >= 3) {
2644
2645        # return $a ** $b if $n == 1;
2646
2647        if ($_[-2] == 1) {
2648            my ($a, $n, $b) = splice @_, -3;
2649            push @_, $a ** $b;
2650            next;
2651        }
2652
2653        # return $a * $b if $n == 0;
2654
2655        if ($_[-2] == 0) {
2656            my ($a, $n, $b) = splice @_, -3;
2657            push @_, $a * $b;
2658            next;
2659        }
2660
2661        # return 1 if $b == 0;
2662
2663        if ($_[-1] == 0) {
2664            splice @_, -3;
2665            push @_, $class -> bone();
2666            next;
2667        }
2668
2669        # return buparrow($a, $n - 1, buparrow($a, $n, $b - 1));
2670
2671        my ($a, $n, $b) = splice @_, -3;
2672        push @_, ($a, $n - 1,
2673                      $a, $n, $b - 1);
2674
2675    }
2676
2677    pop @_;
2678}
2679
2680sub backermann {
2681    my $m = shift;
2682    my $y = $m -> ackermann(@_);
2683    $m -> {value} = $y -> {value};
2684    return $m;
2685}
2686
2687sub ackermann {
2688    # Ackermann's function ackermann(m, n)
2689    #
2690    # The following is a simple, recursive implementation of the ackermann
2691    # function, just to show the idea. Such implementations cause "Deep
2692    # recursion on subroutine ..." warnings, so we use a faster, non-recursive
2693    # algorithm below with @_ as a stack.
2694    #
2695    # sub ackermann {
2696    #     my ($m, $n) = @_;
2697    #     return $n + 1                                  if $m == 0;
2698    #     return ackermann($m - 1, 1)                    if $m > 0 && $n == 0;
2699    #     return ackermann($m - 1, ackermann($m, $n - 1) if $m > 0 && $n > 0;
2700    # }
2701
2702    my ($m, $n) = @_;
2703    my $class = ref $m;
2704    croak("m must be non-negative") if $m < 0;
2705    croak("n must be non-negative") if $n < 0;
2706
2707    my $two      = $class -> new("2");
2708    my $three    = $class -> new("3");
2709    my $thirteen = $class -> new("13");
2710
2711    $n = pop;
2712    $n = $class -> new($n) unless ref($n);
2713    while (@_) {
2714        my $m = pop;
2715        if ($m > $three) {
2716            push @_, (--$m) x $n;
2717            while (--$m >= $three) {
2718                push @_, $m;
2719            }
2720            $n = $thirteen;
2721        } elsif ($m == $three) {
2722            $n = $class -> bone() -> blsft($n + $three) -> bsub($three);
2723        } elsif ($m == $two) {
2724            $n -> bmul($two) -> badd($three);
2725        } elsif ($m >= 0) {
2726            $n -> badd($m) -> binc();
2727        } else {
2728            die "negative m!";
2729        }
2730    }
2731    $n;
2732}
2733
2734sub bsin {
2735    # Calculate sinus(x) to N digits. Unless upgrading is in effect, returns the
2736    # result truncated to an integer.
2737    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
2738
2739    return $x if $x->modify('bsin');
2740
2741    return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN
2742
2743    return $upgrade->new($x)->bsin(@r) if defined $upgrade;
2744
2745    require Math::BigFloat;
2746    # calculate the result and truncate it to integer
2747    my $t = Math::BigFloat->new($x)->bsin(@r)->as_int();
2748
2749    $x->bone() if $t->is_one();
2750    $x->bzero() if $t->is_zero();
2751    $x->round(@r);
2752}
2753
2754sub bcos {
2755    # Calculate cosinus(x) to N digits. Unless upgrading is in effect, returns the
2756    # result truncated to an integer.
2757    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
2758
2759    return $x if $x->modify('bcos');
2760
2761    return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN
2762
2763    return $upgrade->new($x)->bcos(@r) if defined $upgrade;
2764
2765    require Math::BigFloat;
2766    # calculate the result and truncate it to integer
2767    my $t = Math::BigFloat->new($x)->bcos(@r)->as_int();
2768
2769    $x->bone() if $t->is_one();
2770    $x->bzero() if $t->is_zero();
2771    $x->round(@r);
2772}
2773
2774sub batan {
2775    # Calculate arcus tangens of x to N digits. Unless upgrading is in effect, returns the
2776    # result truncated to an integer.
2777    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
2778
2779    return $x if $x->modify('batan');
2780
2781    return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN
2782
2783    return $upgrade->new($x)->batan(@r) if defined $upgrade;
2784
2785    # calculate the result and truncate it to integer
2786    my $tmp = Math::BigFloat->new($x)->batan(@r);
2787
2788    $x->{value} = $LIB->_new($tmp->as_int()->bstr());
2789    $x->round(@r);
2790}
2791
2792sub batan2 {
2793    # calculate arcus tangens of ($y/$x)
2794
2795    # set up parameters
2796    my ($class, $y, $x, @r) = (ref($_[0]), @_);
2797    # objectify is costly, so avoid it
2798    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
2799        ($class, $y, $x, @r) = objectify(2, @_);
2800    }
2801
2802    return $y if $y->modify('batan2');
2803
2804    return $y->bnan() if ($y->{sign} eq $nan) || ($x->{sign} eq $nan);
2805
2806    # Y    X
2807    # != 0 -inf result is +- pi
2808    if ($x->is_inf() || $y->is_inf()) {
2809        # upgrade to Math::BigFloat etc.
2810        return $upgrade->new($y)->batan2($upgrade->new($x), @r) if defined $upgrade;
2811        if ($y->is_inf()) {
2812            if ($x->{sign} eq '-inf') {
2813                # calculate 3 pi/4 => 2.3.. => 2
2814                $y->bone(substr($y->{sign}, 0, 1));
2815                $y->bmul($class->new(2));
2816            } elsif ($x->{sign} eq '+inf') {
2817                # calculate pi/4 => 0.7 => 0
2818                $y->bzero();
2819            } else {
2820                # calculate pi/2 => 1.5 => 1
2821                $y->bone(substr($y->{sign}, 0, 1));
2822            }
2823        } else {
2824            if ($x->{sign} eq '+inf') {
2825                # calculate pi/4 => 0.7 => 0
2826                $y->bzero();
2827            } else {
2828                # PI => 3.1415.. => 3
2829                $y->bone(substr($y->{sign}, 0, 1));
2830                $y->bmul($class->new(3));
2831            }
2832        }
2833        return $y;
2834    }
2835
2836    return $upgrade->new($y)->batan2($upgrade->new($x), @r) if defined $upgrade;
2837
2838    require Math::BigFloat;
2839    my $r = Math::BigFloat->new($y)
2840      ->batan2(Math::BigFloat->new($x), @r)
2841        ->as_int();
2842
2843    $x->{value} = $r->{value};
2844    $x->{sign} = $r->{sign};
2845
2846    $x;
2847}
2848
2849sub bsqrt {
2850    # calculate square root of $x
2851    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
2852
2853    return $x if $x->modify('bsqrt');
2854
2855    return $x->bnan() if $x->{sign} !~ /^\+/; # -x or -inf or NaN => NaN
2856    return $x if $x->{sign} eq '+inf';        # sqrt(+inf) == inf
2857
2858    return $upgrade->bsqrt($x, @r) if defined $upgrade;
2859
2860    $x->{value} = $LIB->_sqrt($x->{value});
2861    $x->round(@r);
2862}
2863
2864sub broot {
2865    # calculate $y'th root of $x
2866
2867    # set up parameters
2868    my ($class, $x, $y, @r) = (ref($_[0]), @_);
2869
2870    $y = $class->new(2) unless defined $y;
2871
2872    # objectify is costly, so avoid it
2873    if ((!ref($x)) || (ref($x) ne ref($y))) {
2874        ($class, $x, $y, @r) = objectify(2, $class || $class, @_);
2875    }
2876
2877    return $x if $x->modify('broot');
2878
2879    # NaN handling: $x ** 1/0, x or y NaN, or y inf/-inf or y == 0
2880    return $x->bnan() if $x->{sign} !~ /^\+/ || $y->is_zero() ||
2881      $y->{sign} !~ /^\+$/;
2882
2883    return $x->round(@r)
2884      if $x->is_zero() || $x->is_one() || $x->is_inf() || $y->is_one();
2885
2886    return $upgrade->new($x)->broot($upgrade->new($y), @r) if defined $upgrade;
2887
2888    $x->{value} = $LIB->_root($x->{value}, $y->{value});
2889    $x->round(@r);
2890}
2891
2892sub bfac {
2893    # (BINT or num_str, BINT or num_str) return BINT
2894    # compute factorial number from $x, modify $x in place
2895    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
2896
2897    return $x if $x->modify('bfac') || $x->{sign} eq '+inf'; # inf => inf
2898    return $x->bnan() if $x->{sign} ne '+'; # NaN, <0 etc => NaN
2899
2900    $x->{value} = $LIB->_fac($x->{value});
2901    $x->round(@r);
2902}
2903
2904sub bdfac {
2905    # compute double factorial, modify $x in place
2906    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
2907
2908    return $x if $x->modify('bdfac') || $x->{sign} eq '+inf'; # inf => inf
2909    return $x->bnan() if $x->{sign} ne '+'; # NaN, <0 etc => NaN
2910
2911    croak("bdfac() requires a newer version of the $LIB library.")
2912        unless $LIB->can('_dfac');
2913
2914    $x->{value} = $LIB->_dfac($x->{value});
2915    $x->round(@r);
2916}
2917
2918sub bfib {
2919    # compute Fibonacci number(s)
2920    my ($class, $x, @r) = objectify(1, @_);
2921
2922    croak("bfib() requires a newer version of the $LIB library.")
2923        unless $LIB->can('_fib');
2924
2925    return $x if $x->modify('bfib');
2926
2927    # List context.
2928
2929    if (wantarray) {
2930        return () if $x ->  is_nan();
2931        croak("bfib() can't return an infinitely long list of numbers")
2932            if $x -> is_inf();
2933
2934        # Use the backend library to compute the first $x Fibonacci numbers.
2935
2936        my @values = $LIB->_fib($x->{value});
2937
2938        # Make objects out of them. The last element in the array is the
2939        # invocand.
2940
2941        for (my $i = 0 ; $i < $#values ; ++ $i) {
2942            my $fib =  $class -> bzero();
2943            $fib -> {value} = $values[$i];
2944            $values[$i] = $fib;
2945        }
2946
2947        $x -> {value} = $values[-1];
2948        $values[-1] = $x;
2949
2950        # If negative, insert sign as appropriate.
2951
2952        if ($x -> is_neg()) {
2953            for (my $i = 2 ; $i <= $#values ; $i += 2) {
2954                $values[$i]{sign} = '-';
2955            }
2956        }
2957
2958        @values = map { $_ -> round(@r) } @values;
2959        return @values;
2960    }
2961
2962    # Scalar context.
2963
2964    else {
2965        return $x if $x->modify('bdfac') || $x ->  is_inf('+');
2966        return $x->bnan() if $x -> is_nan() || $x -> is_inf('-');
2967
2968        $x->{sign}  = $x -> is_neg() && $x -> is_even() ? '-' : '+';
2969        $x->{value} = $LIB->_fib($x->{value});
2970        return $x->round(@r);
2971    }
2972}
2973
2974sub blucas {
2975    # compute Lucas number(s)
2976    my ($class, $x, @r) = objectify(1, @_);
2977
2978    croak("blucas() requires a newer version of the $LIB library.")
2979        unless $LIB->can('_lucas');
2980
2981    return $x if $x->modify('blucas');
2982
2983    # List context.
2984
2985    if (wantarray) {
2986        return () if $x -> is_nan();
2987        croak("blucas() can't return an infinitely long list of numbers")
2988            if $x -> is_inf();
2989
2990        # Use the backend library to compute the first $x Lucas numbers.
2991
2992        my @values = $LIB->_lucas($x->{value});
2993
2994        # Make objects out of them. The last element in the array is the
2995        # invocand.
2996
2997        for (my $i = 0 ; $i < $#values ; ++ $i) {
2998            my $lucas =  $class -> bzero();
2999            $lucas -> {value} = $values[$i];
3000            $values[$i] = $lucas;
3001        }
3002
3003        $x -> {value} = $values[-1];
3004        $values[-1] = $x;
3005
3006        # If negative, insert sign as appropriate.
3007
3008        if ($x -> is_neg()) {
3009            for (my $i = 2 ; $i <= $#values ; $i += 2) {
3010                $values[$i]{sign} = '-';
3011            }
3012        }
3013
3014        @values = map { $_ -> round(@r) } @values;
3015        return @values;
3016    }
3017
3018    # Scalar context.
3019
3020    else {
3021        return $x if $x ->  is_inf('+');
3022        return $x->bnan() if $x -> is_nan() || $x -> is_inf('-');
3023
3024        $x->{sign}  = $x -> is_neg() && $x -> is_even() ? '-' : '+';
3025        $x->{value} = $LIB->_lucas($x->{value});
3026        return $x->round(@r);
3027    }
3028}
3029
3030sub blsft {
3031    # (BINT or num_str, BINT or num_str) return BINT
3032    # compute x << y, base n, y >= 0
3033
3034    my ($class, $x, $y, $b, @r);
3035
3036    # Objectify the base only when it is defined, since an undefined base, as
3037    # in $x->blsft(3) or $x->blog(3, undef) means use the default base 2.
3038
3039    if (!ref($_[0]) && $_[0] =~ /^[A-Za-z]|::/) {
3040        # E.g., Math::BigInt->blog(256, 5, 2)
3041        ($class, $x, $y, $b, @r) =
3042          defined $_[3] ? objectify(3, @_) : objectify(2, @_);
3043    } else {
3044        # E.g., Math::BigInt::blog(256, 5, 2) or $x->blog(5, 2)
3045        ($class, $x, $y, $b, @r) =
3046          defined $_[2] ? objectify(3, @_) : objectify(2, @_);
3047    }
3048
3049    return $x if $x -> modify('blsft');
3050    return $x -> bnan() if ($x -> {sign} !~ /^[+-]$/ ||
3051                            $y -> {sign} !~ /^[+-]$/);
3052    return $x -> round(@r) if $y -> is_zero();
3053
3054    $b = defined($b) ? $b -> numify() : 2;
3055
3056    # While some of the libraries support an arbitrarily large base, not all of
3057    # them do, so rather than returning an incorrect result in those cases,
3058    # disallow bases that don't work with all libraries.
3059
3060    my $uintmax = ~0;
3061    croak("Base is too large.") if $b > $uintmax;
3062
3063    return $x -> bnan() if $b <= 0 || $y -> {sign} eq '-';
3064
3065    $x -> {value} = $LIB -> _lsft($x -> {value}, $y -> {value}, $b);
3066    $x -> round(@r);
3067}
3068
3069sub brsft {
3070    # (BINT or num_str, BINT or num_str) return BINT
3071    # compute x >> y, base n, y >= 0
3072
3073    # set up parameters
3074    my ($class, $x, $y, $b, @r) = (ref($_[0]), @_);
3075
3076    # objectify is costly, so avoid it
3077    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
3078        ($class, $x, $y, $b, @r) = objectify(2, @_);
3079    }
3080
3081    return $x if $x -> modify('brsft');
3082    return $x -> bnan() if ($x -> {sign} !~ /^[+-]$/ || $y -> {sign} !~ /^[+-]$/);
3083    return $x -> round(@r) if $y -> is_zero();
3084    return $x -> bzero(@r) if $x -> is_zero(); # 0 => 0
3085
3086    $b = 2 if !defined $b;
3087    return $x -> bnan() if $b <= 0 || $y -> {sign} eq '-';
3088
3089    # this only works for negative numbers when shifting in base 2
3090    if (($x -> {sign} eq '-') && ($b == 2)) {
3091        return $x -> round(@r) if $x -> is_one('-'); # -1 => -1
3092        if (!$y -> is_one()) {
3093            # although this is O(N*N) in calc (as_bin!) it is O(N) in Pari et
3094            # al but perhaps there is a better emulation for two's complement
3095            # shift...
3096            # if $y != 1, we must simulate it by doing:
3097            # convert to bin, flip all bits, shift, and be done
3098            $x -> binc();           # -3 => -2
3099            my $bin = $x -> as_bin();
3100            $bin =~ s/^-0b//;       # strip '-0b' prefix
3101            $bin =~ tr/10/01/;      # flip bits
3102            # now shift
3103            if ($y >= CORE::length($bin)) {
3104                $bin = '0';         # shifting to far right creates -1
3105                                    # 0, because later increment makes
3106                                    # that 1, attached '-' makes it '-1'
3107                                    # because -1 >> x == -1 !
3108            } else {
3109                $bin =~ s/.{$y}$//; # cut off at the right side
3110                $bin = '1' . $bin;  # extend left side by one dummy '1'
3111                $bin =~ tr/10/01/;  # flip bits back
3112            }
3113            my $res = $class -> new('0b' . $bin); # add prefix and convert back
3114            $res -> binc();                       # remember to increment
3115            $x -> {value} = $res -> {value};      # take over value
3116            return $x -> round(@r); # we are done now, magic, isn't?
3117        }
3118
3119        # x < 0, n == 2, y == 1
3120        $x -> bdec();           # n == 2, but $y == 1: this fixes it
3121    }
3122
3123    $x -> {value} = $LIB -> _rsft($x -> {value}, $y -> {value}, $b);
3124    $x -> round(@r);
3125}
3126
3127###############################################################################
3128# Bitwise methods
3129###############################################################################
3130
3131sub band {
3132    #(BINT or num_str, BINT or num_str) return BINT
3133    # compute x & y
3134
3135    # set up parameters
3136    my ($class, $x, $y, @r) = (ref($_[0]), @_);
3137    # objectify is costly, so avoid it
3138    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
3139        ($class, $x, $y, @r) = objectify(2, @_);
3140    }
3141
3142    return $x if $x->modify('band');
3143
3144    $r[3] = $y;                 # no push!
3145
3146    return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
3147
3148    if ($x->{sign} eq '+' && $y->{sign} eq '+') {
3149        $x->{value} = $LIB->_and($x->{value}, $y->{value});
3150    } else {
3151        ($x->{value}, $x->{sign}) = $LIB->_sand($x->{value}, $x->{sign},
3152                                                $y->{value}, $y->{sign});
3153    }
3154    return $x->round(@r);
3155}
3156
3157sub bior {
3158    #(BINT or num_str, BINT or num_str) return BINT
3159    # compute x | y
3160
3161    # set up parameters
3162    my ($class, $x, $y, @r) = (ref($_[0]), @_);
3163    # objectify is costly, so avoid it
3164    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
3165        ($class, $x, $y, @r) = objectify(2, @_);
3166    }
3167
3168    return $x if $x->modify('bior');
3169
3170    $r[3] = $y;                 # no push!
3171
3172    return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
3173
3174    if ($x->{sign} eq '+' && $y->{sign} eq '+') {
3175        $x->{value} = $LIB->_or($x->{value}, $y->{value});
3176    } else {
3177        ($x->{value}, $x->{sign}) = $LIB->_sor($x->{value}, $x->{sign},
3178                                               $y->{value}, $y->{sign});
3179    }
3180    return $x->round(@r);
3181}
3182
3183sub bxor {
3184    #(BINT or num_str, BINT or num_str) return BINT
3185    # compute x ^ y
3186
3187    # set up parameters
3188    my ($class, $x, $y, @r) = (ref($_[0]), @_);
3189    # objectify is costly, so avoid it
3190    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
3191        ($class, $x, $y, @r) = objectify(2, @_);
3192    }
3193
3194    return $x if $x->modify('bxor');
3195
3196    $r[3] = $y;                 # no push!
3197
3198    return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
3199
3200    if ($x->{sign} eq '+' && $y->{sign} eq '+') {
3201        $x->{value} = $LIB->_xor($x->{value}, $y->{value});
3202    } else {
3203        ($x->{value}, $x->{sign}) = $LIB->_sxor($x->{value}, $x->{sign},
3204                                               $y->{value}, $y->{sign});
3205    }
3206    return $x->round(@r);
3207}
3208
3209sub bnot {
3210    # (num_str or BINT) return BINT
3211    # represent ~x as twos-complement number
3212    # we don't need $class, so undef instead of ref($_[0]) make it slightly faster
3213    my ($class, $x) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
3214
3215    return $x if $x->modify('bnot');
3216    $x->binc()->bneg();         # binc already does round
3217}
3218
3219###############################################################################
3220# Rounding methods
3221###############################################################################
3222
3223sub round {
3224    # Round $self according to given parameters, or given second argument's
3225    # parameters or global defaults
3226
3227    # for speed reasons, _find_round_parameters is embedded here:
3228
3229    my ($self, $a, $p, $r, @args) = @_;
3230    # $a accuracy, if given by caller
3231    # $p precision, if given by caller
3232    # $r round_mode, if given by caller
3233    # @args all 'other' arguments (0 for unary, 1 for binary ops)
3234
3235    my $class = ref($self);       # find out class of argument(s)
3236    no strict 'refs';
3237
3238    # now pick $a or $p, but only if we have got "arguments"
3239    if (!defined $a) {
3240        foreach ($self, @args) {
3241            # take the defined one, or if both defined, the one that is smaller
3242            $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
3243        }
3244    }
3245    if (!defined $p) {
3246        # even if $a is defined, take $p, to signal error for both defined
3247        foreach ($self, @args) {
3248            # take the defined one, or if both defined, the one that is bigger
3249            # -2 > -3, and 3 > 2
3250            $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
3251        }
3252    }
3253
3254    # if still none defined, use globals
3255    unless (defined $a || defined $p) {
3256        $a = ${"$class\::accuracy"};
3257        $p = ${"$class\::precision"};
3258    }
3259
3260    # A == 0 is useless, so undef it to signal no rounding
3261    $a = undef if defined $a && $a == 0;
3262
3263    # no rounding today?
3264    return $self unless defined $a || defined $p; # early out
3265
3266    # set A and set P is an fatal error
3267    return $self->bnan() if defined $a && defined $p;
3268
3269    $r = ${"$class\::round_mode"} unless defined $r;
3270    if ($r !~ /^(even|odd|[+-]inf|zero|trunc|common)$/) {
3271        croak("Unknown round mode '$r'");
3272    }
3273
3274    # now round, by calling either bround or bfround:
3275    if (defined $a) {
3276        $self->bround(int($a), $r) if !defined $self->{_a} || $self->{_a} >= $a;
3277    } else {                  # both can't be undefined due to early out
3278        $self->bfround(int($p), $r) if !defined $self->{_p} || $self->{_p} <= $p;
3279    }
3280
3281    # bround() or bfround() already called bnorm() if nec.
3282    $self;
3283}
3284
3285sub bround {
3286    # accuracy: +$n preserve $n digits from left,
3287    #           -$n preserve $n digits from right (f.i. for 0.1234 style in MBF)
3288    # no-op for $n == 0
3289    # and overwrite the rest with 0's, return normalized number
3290    # do not return $x->bnorm(), but $x
3291
3292    my $x = shift;
3293    $x = __PACKAGE__->new($x) unless ref $x;
3294    my ($scale, $mode) = $x->_scale_a(@_);
3295    return $x if !defined $scale || $x->modify('bround'); # no-op
3296
3297    if ($x->is_zero() || $scale == 0) {
3298        $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
3299        return $x;
3300    }
3301    return $x if $x->{sign} !~ /^[+-]$/; # inf, NaN
3302
3303    # we have fewer digits than we want to scale to
3304    my $len = $x->length();
3305    # convert $scale to a scalar in case it is an object (put's a limit on the
3306    # number length, but this would already limited by memory constraints), makes
3307    # it faster
3308    $scale = $scale->numify() if ref ($scale);
3309
3310    # scale < 0, but > -len (not >=!)
3311    if (($scale < 0 && $scale < -$len-1) || ($scale >= $len)) {
3312        $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
3313        return $x;
3314    }
3315
3316    # count of 0's to pad, from left (+) or right (-): 9 - +6 => 3, or |-6| => 6
3317    my ($pad, $digit_round, $digit_after);
3318    $pad = $len - $scale;
3319    $pad = abs($scale-1) if $scale < 0;
3320
3321    # do not use digit(), it is very costly for binary => decimal
3322    # getting the entire string is also costly, but we need to do it only once
3323    my $xs = $LIB->_str($x->{value});
3324    my $pl = -$pad-1;
3325
3326    # pad:   123: 0 => -1, at 1 => -2, at 2 => -3, at 3 => -4
3327    # pad+1: 123: 0 => 0, at 1 => -1, at 2 => -2, at 3 => -3
3328    $digit_round = '0';
3329    $digit_round = substr($xs, $pl, 1) if $pad <= $len;
3330    $pl++;
3331    $pl ++ if $pad >= $len;
3332    $digit_after = '0';
3333    $digit_after = substr($xs, $pl, 1) if $pad > 0;
3334
3335    # in case of 01234 we round down, for 6789 up, and only in case 5 we look
3336    # closer at the remaining digits of the original $x, remember decision
3337    my $round_up = 1;           # default round up
3338    $round_up -- if
3339      ($mode eq 'trunc')                      ||   # trunc by round down
3340        ($digit_after =~ /[01234]/)           ||   # round down anyway,
3341          # 6789 => round up
3342          ($digit_after eq '5')               &&   # not 5000...0000
3343            ($x->_scan_for_nonzero($pad, $xs, $len) == 0)   &&
3344              (
3345               ($mode eq 'even') && ($digit_round =~ /[24680]/) ||
3346               ($mode eq 'odd')  && ($digit_round =~ /[13579]/) ||
3347               ($mode eq '+inf') && ($x->{sign} eq '-')         ||
3348               ($mode eq '-inf') && ($x->{sign} eq '+')         ||
3349               ($mode eq 'zero') # round down if zero, sign adjusted below
3350              );
3351    my $put_back = 0;           # not yet modified
3352
3353    if (($pad > 0) && ($pad <= $len)) {
3354        substr($xs, -$pad, $pad) = '0' x $pad; # replace with '00...'
3355        $put_back = 1;                         # need to put back
3356    } elsif ($pad > $len) {
3357        $x->bzero();            # round to '0'
3358    }
3359
3360    if ($round_up) {            # what gave test above?
3361        $put_back = 1;                               # need to put back
3362        $pad = $len, $xs = '0' x $pad if $scale < 0; # tlr: whack 0.51=>1.0
3363
3364        # we modify directly the string variant instead of creating a number and
3365        # adding it, since that is faster (we already have the string)
3366        my $c = 0;
3367        $pad ++;                # for $pad == $len case
3368        while ($pad <= $len) {
3369            $c = substr($xs, -$pad, 1) + 1;
3370            $c = '0' if $c eq '10';
3371            substr($xs, -$pad, 1) = $c;
3372            $pad++;
3373            last if $c != 0;    # no overflow => early out
3374        }
3375        $xs = '1'.$xs if $c == 0;
3376
3377    }
3378    $x->{value} = $LIB->_new($xs) if $put_back == 1; # put back, if needed
3379
3380    $x->{_a} = $scale if $scale >= 0;
3381    if ($scale < 0) {
3382        $x->{_a} = $len+$scale;
3383        $x->{_a} = 0 if $scale < -$len;
3384    }
3385    $x;
3386}
3387
3388sub bfround {
3389    # precision: round to the $Nth digit left (+$n) or right (-$n) from the '.'
3390    # $n == 0 || $n == 1 => round to integer
3391    my $x = shift;
3392    my $class = ref($x) || $x;
3393    $x = $class->new($x) unless ref $x;
3394
3395    my ($scale, $mode) = $x->_scale_p(@_);
3396
3397    return $x if !defined $scale || $x->modify('bfround'); # no-op
3398
3399    # no-op for Math::BigInt objects if $n <= 0
3400    $x->bround($x->length()-$scale, $mode) if $scale > 0;
3401
3402    delete $x->{_a};            # delete to save memory
3403    $x->{_p} = $scale;          # store new _p
3404    $x;
3405}
3406
3407sub fround {
3408    # Exists to make life easier for switch between MBF and MBI (should we
3409    # autoload fxxx() like MBF does for bxxx()?)
3410    my $x = shift;
3411    $x = __PACKAGE__->new($x) unless ref $x;
3412    $x->bround(@_);
3413}
3414
3415sub bfloor {
3416    # round towards minus infinity; no-op since it's already integer
3417    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
3418
3419    $x->round(@r);
3420}
3421
3422sub bceil {
3423    # round towards plus infinity; no-op since it's already int
3424    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
3425
3426    $x->round(@r);
3427}
3428
3429sub bint {
3430    # round towards zero; no-op since it's already integer
3431    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
3432
3433    $x->round(@r);
3434}
3435
3436###############################################################################
3437# Other mathematical methods
3438###############################################################################
3439
3440sub bgcd {
3441    # (BINT or num_str, BINT or num_str) return BINT
3442    # does not modify arguments, but returns new object
3443    # GCD -- Euclid's algorithm, variant C (Knuth Vol 3, pg 341 ff)
3444
3445    my ($class, @args) = objectify(0, @_);
3446
3447    my $x = shift @args;
3448    $x = ref($x) && $x -> isa($class) ? $x -> copy() : $class -> new($x);
3449
3450    return $class->bnan() if $x->{sign} !~ /^[+-]$/;    # x NaN?
3451
3452    while (@args) {
3453        my $y = shift @args;
3454        $y = $class->new($y) unless ref($y) && $y -> isa($class);
3455        return $class->bnan() if $y->{sign} !~ /^[+-]$/;    # y NaN?
3456        $x->{value} = $LIB->_gcd($x->{value}, $y->{value});
3457        last if $LIB->_is_one($x->{value});
3458    }
3459
3460    return $x -> babs();
3461}
3462
3463sub blcm {
3464    # (BINT or num_str, BINT or num_str) return BINT
3465    # does not modify arguments, but returns new object
3466    # Least Common Multiple
3467
3468    my ($class, @args) = objectify(0, @_);
3469
3470    my $x = shift @args;
3471    $x = ref($x) && $x -> isa($class) ? $x -> copy() : $class -> new($x);
3472    return $class->bnan() if $x->{sign} !~ /^[+-]$/;    # x NaN?
3473
3474    while (@args) {
3475        my $y = shift @args;
3476        $y = $class -> new($y) unless ref($y) && $y -> isa($class);
3477        return $x->bnan() if $y->{sign} !~ /^[+-]$/;     # y not integer
3478        $x -> {value} = $LIB->_lcm($x -> {value}, $y -> {value});
3479    }
3480
3481    return $x -> babs();
3482}
3483
3484###############################################################################
3485# Object property methods
3486###############################################################################
3487
3488sub sign {
3489    # return the sign of the number: +/-/-inf/+inf/NaN
3490    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
3491
3492    $x->{sign};
3493}
3494
3495sub digit {
3496    # return the nth decimal digit, negative values count backward, 0 is right
3497    my ($class, $x, $n) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
3498
3499    $n = $n->numify() if ref($n);
3500    $LIB->_digit($x->{value}, $n || 0);
3501}
3502
3503sub bdigitsum {
3504    # like digitsum(), but assigns the result to the invocand
3505    my $x = shift;
3506
3507    return $x           if $x -> is_nan();
3508    return $x -> bnan() if $x -> is_inf();
3509
3510    $x -> {value} = $LIB -> _digitsum($x -> {value});
3511    $x -> {sign}  = '+';
3512    return $x;
3513}
3514
3515sub digitsum {
3516    # compute sum of decimal digits and return it
3517    my $x = shift;
3518    my $class = ref $x;
3519
3520    return $class -> bnan() if $x -> is_nan();
3521    return $class -> bnan() if $x -> is_inf();
3522
3523    my $y = $class -> bzero();
3524    $y -> {value} = $LIB -> _digitsum($x -> {value});
3525    return $y;
3526}
3527
3528sub length {
3529    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
3530
3531    my $e = $LIB->_len($x->{value});
3532    wantarray ? ($e, 0) : $e;
3533}
3534
3535sub exponent {
3536    # return a copy of the exponent (here always 0, NaN or 1 for $m == 0)
3537    my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);
3538
3539    if ($x->{sign} !~ /^[+-]$/) {
3540        my $s = $x->{sign};
3541        $s =~ s/^[+-]//; # NaN, -inf, +inf => NaN or inf
3542        return $class->new($s);
3543    }
3544    return $class->bzero() if $x->is_zero();
3545
3546    # 12300 => 2 trailing zeros => exponent is 2
3547    $class->new($LIB->_zeros($x->{value}));
3548}
3549
3550sub mantissa {
3551    # return the mantissa (compatible to Math::BigFloat, e.g. reduced)
3552    my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);
3553
3554    if ($x->{sign} !~ /^[+-]$/) {
3555        # for NaN, +inf, -inf: keep the sign
3556        return $class->new($x->{sign});
3557    }
3558    my $m = $x->copy();
3559    delete $m->{_p};
3560    delete $m->{_a};
3561
3562    # that's a bit inefficient:
3563    my $zeros = $LIB->_zeros($m->{value});
3564    $m->brsft($zeros, 10) if $zeros != 0;
3565    $m;
3566}
3567
3568sub parts {
3569    # return a copy of both the exponent and the mantissa
3570    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
3571
3572    ($x->mantissa(), $x->exponent());
3573}
3574
3575sub sparts {
3576    my $self  = shift;
3577    my $class = ref $self;
3578
3579    croak("sparts() is an instance method, not a class method")
3580        unless $class;
3581
3582    # Not-a-number.
3583
3584    if ($self -> is_nan()) {
3585        my $mant = $self -> copy();             # mantissa
3586        return $mant unless wantarray;          # scalar context
3587        my $expo = $class -> bnan();            # exponent
3588        return ($mant, $expo);                  # list context
3589    }
3590
3591    # Infinity.
3592
3593    if ($self -> is_inf()) {
3594        my $mant = $self -> copy();             # mantissa
3595        return $mant unless wantarray;          # scalar context
3596        my $expo = $class -> binf('+');         # exponent
3597        return ($mant, $expo);                  # list context
3598    }
3599
3600    # Finite number.
3601
3602    my $mant   = $self -> copy();
3603    my $nzeros = $LIB -> _zeros($mant -> {value});
3604
3605    $mant -> brsft($nzeros, 10) if $nzeros != 0;
3606    return $mant unless wantarray;
3607
3608    my $expo = $class -> new($nzeros);
3609    return ($mant, $expo);
3610}
3611
3612sub nparts {
3613    my $self  = shift;
3614    my $class = ref $self;
3615
3616    croak("nparts() is an instance method, not a class method")
3617        unless $class;
3618
3619    # Not-a-number.
3620
3621    if ($self -> is_nan()) {
3622        my $mant = $self -> copy();             # mantissa
3623        return $mant unless wantarray;          # scalar context
3624        my $expo = $class -> bnan();            # exponent
3625        return ($mant, $expo);                  # list context
3626    }
3627
3628    # Infinity.
3629
3630    if ($self -> is_inf()) {
3631        my $mant = $self -> copy();             # mantissa
3632        return $mant unless wantarray;          # scalar context
3633        my $expo = $class -> binf('+');         # exponent
3634        return ($mant, $expo);                  # list context
3635    }
3636
3637    # Finite number.
3638
3639    my ($mant, $expo) = $self -> sparts();
3640
3641    if ($mant -> bcmp(0)) {
3642        my ($ndigtot, $ndigfrac) = $mant -> length();
3643        my $expo10adj = $ndigtot - $ndigfrac - 1;
3644
3645        if ($expo10adj != 0) {
3646            return $upgrade -> new($self) -> nparts() if $upgrade;
3647            $mant -> bnan();
3648            return $mant unless wantarray;
3649            $expo -> badd($expo10adj);
3650            return ($mant, $expo);
3651        }
3652    }
3653
3654    return $mant unless wantarray;
3655    return ($mant, $expo);
3656}
3657
3658sub eparts {
3659    my $self  = shift;
3660    my $class = ref $self;
3661
3662    croak("eparts() is an instance method, not a class method")
3663        unless $class;
3664
3665    # Not-a-number and Infinity.
3666
3667    return $self -> sparts() if $self -> is_nan() || $self -> is_inf();
3668
3669    # Finite number.
3670
3671    my ($mant, $expo) = $self -> sparts();
3672
3673    if ($mant -> bcmp(0)) {
3674        my $ndigmant  = $mant -> length();
3675        $expo -> badd($ndigmant);
3676
3677        # $c is the number of digits that will be in the integer part of the
3678        # final mantissa.
3679
3680        my $c = $expo -> copy() -> bdec() -> bmod(3) -> binc();
3681        $expo -> bsub($c);
3682
3683        if ($ndigmant > $c) {
3684            return $upgrade -> new($self) -> eparts() if $upgrade;
3685            $mant -> bnan();
3686            return $mant unless wantarray;
3687            return ($mant, $expo);
3688        }
3689
3690        $mant -> blsft($c - $ndigmant, 10);
3691    }
3692
3693    return $mant unless wantarray;
3694    return ($mant, $expo);
3695}
3696
3697sub dparts {
3698    my $self  = shift;
3699    my $class = ref $self;
3700
3701    croak("dparts() is an instance method, not a class method")
3702        unless $class;
3703
3704    my $int = $self -> copy();
3705    return $int unless wantarray;
3706
3707    my $frc = $class -> bzero();
3708    return ($int, $frc);
3709}
3710
3711###############################################################################
3712# String conversion methods
3713###############################################################################
3714
3715sub bstr {
3716    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
3717
3718    if ($x->{sign} ne '+' && $x->{sign} ne '-') {
3719        return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN
3720        return 'inf';                                  # +inf
3721    }
3722    my $str = $LIB->_str($x->{value});
3723    return $x->{sign} eq '-' ? "-$str" : $str;
3724}
3725
3726# Scientific notation with significand/mantissa as an integer, e.g., "12345" is
3727# written as "1.2345e+4".
3728
3729sub bsstr {
3730    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
3731
3732    if ($x->{sign} ne '+' && $x->{sign} ne '-') {
3733        return $x->{sign} unless $x->{sign} eq '+inf';  # -inf, NaN
3734        return 'inf';                                   # +inf
3735    }
3736    my ($m, $e) = $x -> parts();
3737    my $str = $LIB->_str($m->{value}) . 'e+' . $LIB->_str($e->{value});
3738    return $x->{sign} eq '-' ? "-$str" : $str;
3739}
3740
3741# Normalized notation, e.g., "12345" is written as "12345e+0".
3742
3743sub bnstr {
3744    my $x = shift;
3745
3746    if ($x->{sign} ne '+' && $x->{sign} ne '-') {
3747        return $x->{sign} unless $x->{sign} eq '+inf';  # -inf, NaN
3748        return 'inf';                                   # +inf
3749    }
3750
3751    return $x -> bstr() if $x -> is_nan() || $x -> is_inf();
3752
3753    my ($mant, $expo) = $x -> parts();
3754
3755    # The "fraction posision" is the position (offset) for the decimal point
3756    # relative to the end of the digit string.
3757
3758    my $fracpos = $mant -> length() - 1;
3759    if ($fracpos == 0) {
3760        my $str = $LIB->_str($mant->{value}) . "e+" . $LIB->_str($expo->{value});
3761        return $x->{sign} eq '-' ? "-$str" : $str;
3762    }
3763
3764    $expo += $fracpos;
3765    my $mantstr = $LIB->_str($mant -> {value});
3766    substr($mantstr, -$fracpos, 0) = '.';
3767
3768    my $str = $mantstr . 'e+' . $LIB->_str($expo -> {value});
3769    return $x->{sign} eq '-' ? "-$str" : $str;
3770}
3771
3772# Engineering notation, e.g., "12345" is written as "12.345e+3".
3773
3774sub bestr {
3775    my $x = shift;
3776
3777    if ($x->{sign} ne '+' && $x->{sign} ne '-') {
3778        return $x->{sign} unless $x->{sign} eq '+inf';  # -inf, NaN
3779        return 'inf';                                   # +inf
3780    }
3781
3782    my ($mant, $expo) = $x -> parts();
3783
3784    my $sign = $mant -> sign();
3785    $mant -> babs();
3786
3787    my $mantstr = $LIB->_str($mant -> {value});
3788    my $mantlen = CORE::length($mantstr);
3789
3790    my $dotidx = 1;
3791    $expo += $mantlen - 1;
3792
3793    my $c = $expo -> copy() -> bmod(3);
3794    $expo   -= $c;
3795    $dotidx += $c;
3796
3797    if ($mantlen < $dotidx) {
3798        $mantstr .= "0" x ($dotidx - $mantlen);
3799    } elsif ($mantlen > $dotidx) {
3800        substr($mantstr, $dotidx, 0) = ".";
3801    }
3802
3803    my $str = $mantstr . 'e+' . $LIB->_str($expo -> {value});
3804    return $sign eq "-" ? "-$str" : $str;
3805}
3806
3807# Decimal notation, e.g., "12345".
3808
3809sub bdstr {
3810    my $x = shift;
3811
3812    if ($x->{sign} ne '+' && $x->{sign} ne '-') {
3813        return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN
3814        return 'inf';                                  # +inf
3815    }
3816
3817    my $str = $LIB->_str($x->{value});
3818    return $x->{sign} eq '-' ? "-$str" : $str;
3819}
3820
3821sub to_hex {
3822    # return as hex string, with prefixed 0x
3823    my $x = shift;
3824    $x = __PACKAGE__->new($x) if !ref($x);
3825
3826    return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
3827
3828    my $hex = $LIB->_to_hex($x->{value});
3829    return $x->{sign} eq '-' ? "-$hex" : $hex;
3830}
3831
3832sub to_oct {
3833    # return as octal string, with prefixed 0
3834    my $x = shift;
3835    $x = __PACKAGE__->new($x) if !ref($x);
3836
3837    return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
3838
3839    my $oct = $LIB->_to_oct($x->{value});
3840    return $x->{sign} eq '-' ? "-$oct" : $oct;
3841}
3842
3843sub to_bin {
3844    # return as binary string, with prefixed 0b
3845    my $x = shift;
3846    $x = __PACKAGE__->new($x) if !ref($x);
3847
3848    return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
3849
3850    my $bin = $LIB->_to_bin($x->{value});
3851    return $x->{sign} eq '-' ? "-$bin" : $bin;
3852}
3853
3854sub to_bytes {
3855    # return a byte string
3856    my $x = shift;
3857    $x = __PACKAGE__->new($x) if !ref($x);
3858
3859    croak("to_bytes() requires a finite, non-negative integer")
3860        if $x -> is_neg() || ! $x -> is_int();
3861
3862    croak("to_bytes() requires a newer version of the $LIB library.")
3863        unless $LIB->can('_to_bytes');
3864
3865    return $LIB->_to_bytes($x->{value});
3866}
3867
3868sub to_base {
3869    # return a base anything string
3870    my $x = shift;
3871    $x = __PACKAGE__->new($x) if !ref($x);
3872
3873    croak("the value to convert must be a finite, non-negative integer")
3874      if $x -> is_neg() || !$x -> is_int();
3875
3876    my $base = shift;
3877    $base = __PACKAGE__->new($base) unless ref($base);
3878
3879    croak("the base must be a finite integer >= 2")
3880      if $base < 2 || ! $base -> is_int();
3881
3882    # If no collating sequence is given, pass some of the conversions to
3883    # methods optimized for those cases.
3884
3885    if (! @_) {
3886        return    $x -> to_bin() if $base == 2;
3887        return    $x -> to_oct() if $base == 8;
3888        return uc $x -> to_hex() if $base == 16;
3889        return    $x -> bstr()   if $base == 10;
3890    }
3891
3892    croak("to_base() requires a newer version of the $LIB library.")
3893      unless $LIB->can('_to_base');
3894
3895    return $LIB->_to_base($x->{value}, $base -> {value}, @_ ? shift() : ());
3896}
3897
3898sub as_hex {
3899    # return as hex string, with prefixed 0x
3900    my $x = shift;
3901    $x = __PACKAGE__->new($x) if !ref($x);
3902
3903    return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
3904
3905    my $hex = $LIB->_as_hex($x->{value});
3906    return $x->{sign} eq '-' ? "-$hex" : $hex;
3907}
3908
3909sub as_oct {
3910    # return as octal string, with prefixed 0
3911    my $x = shift;
3912    $x = __PACKAGE__->new($x) if !ref($x);
3913
3914    return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
3915
3916    my $oct = $LIB->_as_oct($x->{value});
3917    return $x->{sign} eq '-' ? "-$oct" : $oct;
3918}
3919
3920sub as_bin {
3921    # return as binary string, with prefixed 0b
3922    my $x = shift;
3923    $x = __PACKAGE__->new($x) if !ref($x);
3924
3925    return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
3926
3927    my $bin = $LIB->_as_bin($x->{value});
3928    return $x->{sign} eq '-' ? "-$bin" : $bin;
3929}
3930
3931*as_bytes = \&to_bytes;
3932
3933###############################################################################
3934# Other conversion methods
3935###############################################################################
3936
3937sub numify {
3938    # Make a Perl scalar number from a Math::BigInt object.
3939    my $x = shift;
3940    $x = __PACKAGE__->new($x) unless ref $x;
3941
3942    if ($x -> is_nan()) {
3943        require Math::Complex;
3944        my $inf = Math::Complex::Inf();
3945        return $inf - $inf;
3946    }
3947
3948    if ($x -> is_inf()) {
3949        require Math::Complex;
3950        my $inf = Math::Complex::Inf();
3951        return $x -> is_negative() ? -$inf : $inf;
3952    }
3953
3954    my $num = 0 + $LIB->_num($x->{value});
3955    return $x->{sign} eq '-' ? -$num : $num;
3956}
3957
3958###############################################################################
3959# Private methods and functions.
3960###############################################################################
3961
3962sub objectify {
3963    # Convert strings and "foreign objects" to the objects we want.
3964
3965    # The first argument, $count, is the number of following arguments that
3966    # objectify() looks at and converts to objects. The first is a classname.
3967    # If the given count is 0, all arguments will be used.
3968
3969    # After the count is read, objectify obtains the name of the class to which
3970    # the following arguments are converted. If the second argument is a
3971    # reference, use the reference type as the class name. Otherwise, if it is
3972    # a string that looks like a class name, use that. Otherwise, use $class.
3973
3974    # Caller:                        Gives us:
3975    #
3976    # $x->badd(1);                => ref x, scalar y
3977    # Class->badd(1, 2);           => classname x (scalar), scalar x, scalar y
3978    # Class->badd(Class->(1), 2);  => classname x (scalar), ref x, scalar y
3979    # Math::BigInt::badd(1, 2);    => scalar x, scalar y
3980
3981    # A shortcut for the common case $x->unary_op(), in which case the argument
3982    # list is (0, $x) or (1, $x).
3983
3984    return (ref($_[1]), $_[1]) if @_ == 2 && ($_[0] || 0) == 1 && ref($_[1]);
3985
3986    # Check the context.
3987
3988    unless (wantarray) {
3989        croak(__PACKAGE__ . "::objectify() needs list context");
3990    }
3991
3992    # Get the number of arguments to objectify.
3993
3994    my $count = shift;
3995
3996    # Initialize the output array.
3997
3998    my @a = @_;
3999
4000    # If the first argument is a reference, use that reference type as our
4001    # class name. Otherwise, if the first argument looks like a class name,
4002    # then use that as our class name. Otherwise, use the default class name.
4003
4004    my $class;
4005    if (ref($a[0])) {                   # reference?
4006        $class = ref($a[0]);
4007    } elsif ($a[0] =~ /^[A-Z].*::/) {   # string with class name?
4008        $class = shift @a;
4009    } else {
4010        $class = __PACKAGE__;           # default class name
4011    }
4012
4013    $count ||= @a;
4014    unshift @a, $class;
4015
4016    no strict 'refs';
4017
4018    # What we upgrade to, if anything.
4019
4020    my $up = ${"$a[0]::upgrade"};
4021
4022    # Disable downgrading, because Math::BigFloat -> foo('1.0', '2.0') needs
4023    # floats.
4024
4025    my $down;
4026    if (defined ${"$a[0]::downgrade"}) {
4027        $down = ${"$a[0]::downgrade"};
4028        ${"$a[0]::downgrade"} = undef;
4029    }
4030
4031    for my $i (1 .. $count) {
4032
4033        my $ref = ref $a[$i];
4034
4035        # Perl scalars are fed to the appropriate constructor.
4036
4037        unless ($ref) {
4038            $a[$i] = $a[0] -> new($a[$i]);
4039            next;
4040        }
4041
4042        # If it is an object of the right class, all is fine.
4043
4044        next if $ref -> isa($a[0]);
4045
4046        # Upgrading is OK, so skip further tests if the argument is upgraded.
4047
4048        if (defined $up && $ref -> isa($up)) {
4049            next;
4050        }
4051
4052        # See if we can call one of the as_xxx() methods. We don't know whether
4053        # the as_xxx() method returns an object or a scalar, so re-check
4054        # afterwards.
4055
4056        my $recheck = 0;
4057
4058        if ($a[0] -> isa('Math::BigInt')) {
4059            if ($a[$i] -> can('as_int')) {
4060                $a[$i] = $a[$i] -> as_int();
4061                $recheck = 1;
4062            } elsif ($a[$i] -> can('as_number')) {
4063                $a[$i] = $a[$i] -> as_number();
4064                $recheck = 1;
4065            }
4066        }
4067
4068        elsif ($a[0] -> isa('Math::BigFloat')) {
4069            if ($a[$i] -> can('as_float')) {
4070                $a[$i] = $a[$i] -> as_float();
4071                $recheck = $1;
4072            }
4073        }
4074
4075        # If we called one of the as_xxx() methods, recheck.
4076
4077        if ($recheck) {
4078            $ref = ref($a[$i]);
4079
4080            # Perl scalars are fed to the appropriate constructor.
4081
4082            unless ($ref) {
4083                $a[$i] = $a[0] -> new($a[$i]);
4084                next;
4085            }
4086
4087            # If it is an object of the right class, all is fine.
4088
4089            next if $ref -> isa($a[0]);
4090        }
4091
4092        # Last resort.
4093
4094        $a[$i] = $a[0] -> new($a[$i]);
4095    }
4096
4097    # Reset the downgrading.
4098
4099    ${"$a[0]::downgrade"} = $down;
4100
4101    return @a;
4102}
4103
4104sub import {
4105    my $class = shift;
4106    $IMPORT++;                  # remember we did import()
4107    my @a;                      # unrecognized arguments
4108    my $warn_or_die = 0;        # 0 - no warn, 1 - warn, 2 - die
4109    for (my $i = 0; $i <= $#_ ; $i++) {
4110        if ($_[$i] eq ':constant') {
4111            # this causes overlord er load to step in
4112            overload::constant
4113                integer => sub { $class->new(shift) },
4114                binary  => sub { $class->new(shift) };
4115        } elsif ($_[$i] eq 'upgrade') {
4116            # this causes upgrading
4117            $upgrade = $_[$i+1]; # or undef to disable
4118            $i++;
4119        } elsif ($_[$i] =~ /^(lib|try|only)\z/) {
4120            # this causes a different low lib to take care...
4121            $LIB = $_[$i+1] || '';
4122            # try  => 0 (no warn)
4123            # lib  => 1 (warn on fallback)
4124            # only => 2 (die on fallback)
4125            $warn_or_die = 1 if $_[$i] eq 'lib';
4126            $warn_or_die = 2 if $_[$i] eq 'only';
4127            $i++;
4128        } else {
4129            push @a, $_[$i];
4130        }
4131    }
4132    # any non :constant stuff is handled by our parent, Exporter
4133    if (@a > 0) {
4134        $class->SUPER::import(@a);            # need it for subclasses
4135        $class->export_to_level(1, $class, @a); # need it for MBF
4136    }
4137
4138    # try to load core math lib
4139    my @c = split /\s*,\s*/, $LIB;
4140    foreach (@c) {
4141        tr/a-zA-Z0-9://cd;      # limit to sane characters
4142    }
4143    push @c, \'Calc'            # if all fail, try these
4144      if $warn_or_die < 2;      # but not for "only"
4145    $LIB = '';                  # signal error
4146    foreach my $l (@c) {
4147        # fallback libraries are "marked" as \'string', extract string if nec.
4148        my $lib = $l;
4149        $lib = $$l if ref($l);
4150
4151        next unless defined($lib) && CORE::length($lib);
4152        $lib = 'Math::BigInt::'.$lib if $lib !~ /^Math::BigInt/i;
4153        $lib =~ s/\.pm$//;
4154        my @parts = split /::/, $lib;   # Math::BigInt => Math BigInt
4155        $parts[-1] .= '.pm';            # BigInt => BigInt.pm
4156        require File::Spec;
4157        my $file = File::Spec->catfile(@parts);
4158        eval { require $file; };
4159        if ($@ eq '') {
4160            $lib->import();
4161            $LIB = $lib;
4162            if ($warn_or_die > 0 && ref($l)) {
4163                my $msg = "Math::BigInt: couldn't load specified"
4164                        . " math lib(s), fallback to $lib";
4165                carp($msg)  if $warn_or_die == 1;
4166                croak($msg) if $warn_or_die == 2;
4167            }
4168            last;               # found a usable one, break
4169        }
4170    }
4171    if ($LIB eq '') {
4172        if ($warn_or_die == 2) {
4173            croak("Couldn't load specified math lib(s)" .
4174                        " and fallback disallowed");
4175        } else {
4176            croak("Couldn't load any math lib(s), not even fallback to Calc.pm");
4177        }
4178    }
4179
4180    # notify callbacks
4181    foreach my $class (keys %CALLBACKS) {
4182        &{$CALLBACKS{$class}}($LIB);
4183    }
4184
4185    # import done
4186}
4187
4188sub _register_callback {
4189    my ($class, $callback) = @_;
4190
4191    if (ref($callback) ne 'CODE') {
4192        croak("$callback is not a coderef");
4193    }
4194    $CALLBACKS{$class} = $callback;
4195}
4196
4197sub _split_dec_string {
4198    my $str = shift;
4199
4200    if ($str =~ s/
4201                     ^
4202
4203                     # leading whitespace
4204                     ( \s* )
4205
4206                     # optional sign
4207                     ( [+-]? )
4208
4209                     # significand
4210                     (
4211                         \d+ (?: _ \d+ )*
4212                         (?:
4213                             \.
4214                             (?: \d+ (?: _ \d+ )* )?
4215                         )?
4216                     |
4217                         \.
4218                         \d+ (?: _ \d+ )*
4219                     )
4220
4221                     # optional exponent
4222                     (?:
4223                         [Ee]
4224                         ( [+-]? )
4225                         ( \d+ (?: _ \d+ )* )
4226                     )?
4227
4228                     # trailing stuff
4229                     ( \D .*? )?
4230
4231                     \z
4232                 //x) {
4233        my $leading         = $1;
4234        my $significand_sgn = $2 || '+';
4235        my $significand_abs = $3;
4236        my $exponent_sgn    = $4 || '+';
4237        my $exponent_abs    = $5 || '0';
4238        my $trailing        = $6;
4239
4240        # Remove underscores and leading zeros.
4241
4242        $significand_abs =~ tr/_//d;
4243        $exponent_abs    =~ tr/_//d;
4244
4245        $significand_abs =~ s/^0+(.)/$1/;
4246        $exponent_abs    =~ s/^0+(.)/$1/;
4247
4248        # If the significand contains a dot, remove it and adjust the exponent
4249        # accordingly. E.g., "1234.56789e+3" -> "123456789e-2"
4250
4251        my $idx = index $significand_abs, '.';
4252        if ($idx > -1) {
4253            $significand_abs =~ s/0+\z//;
4254            substr($significand_abs, $idx, 1) = '';
4255            my $exponent = $exponent_sgn . $exponent_abs;
4256            $exponent .= $idx - CORE::length($significand_abs);
4257            $exponent_abs = abs $exponent;
4258            $exponent_sgn = $exponent < 0 ? '-' : '+';
4259        }
4260
4261        return($leading,
4262               $significand_sgn, $significand_abs,
4263               $exponent_sgn, $exponent_abs,
4264               $trailing);
4265    }
4266
4267    return undef;
4268}
4269
4270sub _split {
4271    # input: num_str; output: undef for invalid or
4272    # (\$mantissa_sign, \$mantissa_value, \$mantissa_fraction,
4273    # \$exp_sign, \$exp_value)
4274    # Internal, take apart a string and return the pieces.
4275    # Strip leading/trailing whitespace, leading zeros, underscore and reject
4276    # invalid input.
4277    my $x = shift;
4278
4279    # strip white space at front, also extraneous leading zeros
4280    $x =~ s/^\s*([-]?)0*([0-9])/$1$2/g; # will not strip '  .2'
4281    $x =~ s/^\s+//;                     # but this will
4282    $x =~ s/\s+$//g;                    # strip white space at end
4283
4284    # shortcut, if nothing to split, return early
4285    if ($x =~ /^[+-]?[0-9]+\z/) {
4286        $x =~ s/^([+-])0*([0-9])/$2/;
4287        my $sign = $1 || '+';
4288        return (\$sign, \$x, \'', \'', \0);
4289    }
4290
4291    # invalid starting char?
4292    return if $x !~ /^[+-]?(\.?[0-9]|0b[0-1]|0x[0-9a-fA-F])/;
4293
4294    return Math::BigInt->from_hex($x) if $x =~ /^[+-]?0x/; # hex string
4295    return Math::BigInt->from_bin($x) if $x =~ /^[+-]?0b/; # binary string
4296
4297    # strip underscores between digits
4298    $x =~ s/([0-9])_([0-9])/$1$2/g;
4299    $x =~ s/([0-9])_([0-9])/$1$2/g; # do twice for 1_2_3
4300
4301    # some possible inputs:
4302    # 2.1234 # 0.12        # 1          # 1E1 # 2.134E1 # 434E-10 # 1.02009E-2
4303    # .2     # 1_2_3.4_5_6 # 1.4E1_2_3  # 1e3 # +.2     # 0e999
4304
4305    my ($m, $e, $last) = split /[Ee]/, $x;
4306    return if defined $last;    # last defined => 1e2E3 or others
4307    $e = '0' if !defined $e || $e eq "";
4308
4309    # sign, value for exponent, mantint, mantfrac
4310    my ($es, $ev, $mis, $miv, $mfv);
4311    # valid exponent?
4312    if ($e =~ /^([+-]?)0*([0-9]+)$/) # strip leading zeros
4313    {
4314        $es = $1;
4315        $ev = $2;
4316        # valid mantissa?
4317        return if $m eq '.' || $m eq '';
4318        my ($mi, $mf, $lastf) = split /\./, $m;
4319        return if defined $lastf; # lastf defined => 1.2.3 or others
4320        $mi = '0' if !defined $mi;
4321        $mi .= '0' if $mi =~ /^[\-\+]?$/;
4322        $mf = '0' if !defined $mf || $mf eq '';
4323        if ($mi =~ /^([+-]?)0*([0-9]+)$/) # strip leading zeros
4324        {
4325            $mis = $1 || '+';
4326            $miv = $2;
4327            return unless ($mf =~ /^([0-9]*?)0*$/); # strip trailing zeros
4328            $mfv = $1;
4329            # handle the 0e999 case here
4330            $ev = 0 if $miv eq '0' && $mfv eq '';
4331            return (\$mis, \$miv, \$mfv, \$es, \$ev);
4332        }
4333    }
4334    return;                     # NaN, not a number
4335}
4336
4337sub _trailing_zeros {
4338    # return the amount of trailing zeros in $x (as scalar)
4339    my $x = shift;
4340    $x = __PACKAGE__->new($x) unless ref $x;
4341
4342    return 0 if $x->{sign} !~ /^[+-]$/; # NaN, inf, -inf etc
4343
4344    $LIB->_zeros($x->{value}); # must handle odd values, 0 etc
4345}
4346
4347sub _scan_for_nonzero {
4348    # internal, used by bround() to scan for non-zeros after a '5'
4349    my ($x, $pad, $xs, $len) = @_;
4350
4351    return 0 if $len == 1;      # "5" is trailed by invisible zeros
4352    my $follow = $pad - 1;
4353    return 0 if $follow > $len || $follow < 1;
4354
4355    # use the string form to check whether only '0's follow or not
4356    substr ($xs, -$follow) =~ /[^0]/ ? 1 : 0;
4357}
4358
4359sub _find_round_parameters {
4360    # After any operation or when calling round(), the result is rounded by
4361    # regarding the A & P from arguments, local parameters, or globals.
4362
4363    # !!!!!!! If you change this, remember to change round(), too! !!!!!!!!!!
4364
4365    # This procedure finds the round parameters, but it is for speed reasons
4366    # duplicated in round. Otherwise, it is tested by the testsuite and used
4367    # by bdiv().
4368
4369    # returns ($self) or ($self, $a, $p, $r) - sets $self to NaN of both A and P
4370    # were requested/defined (locally or globally or both)
4371
4372    my ($self, $a, $p, $r, @args) = @_;
4373    # $a accuracy, if given by caller
4374    # $p precision, if given by caller
4375    # $r round_mode, if given by caller
4376    # @args all 'other' arguments (0 for unary, 1 for binary ops)
4377
4378    my $class = ref($self);       # find out class of argument(s)
4379    no strict 'refs';
4380
4381    # convert to normal scalar for speed and correctness in inner parts
4382    $a = $a->can('numify') ? $a->numify() : "$a" if defined $a && ref($a);
4383    $p = $p->can('numify') ? $p->numify() : "$p" if defined $p && ref($p);
4384
4385    # now pick $a or $p, but only if we have got "arguments"
4386    if (!defined $a) {
4387        foreach ($self, @args) {
4388            # take the defined one, or if both defined, the one that is smaller
4389            $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
4390        }
4391    }
4392    if (!defined $p) {
4393        # even if $a is defined, take $p, to signal error for both defined
4394        foreach ($self, @args) {
4395            # take the defined one, or if both defined, the one that is bigger
4396            # -2 > -3, and 3 > 2
4397            $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
4398        }
4399    }
4400
4401    # if still none defined, use globals (#2)
4402    $a = ${"$class\::accuracy"}  unless defined $a;
4403    $p = ${"$class\::precision"} unless defined $p;
4404
4405    # A == 0 is useless, so undef it to signal no rounding
4406    $a = undef if defined $a && $a == 0;
4407
4408    # no rounding today?
4409    return ($self) unless defined $a || defined $p; # early out
4410
4411    # set A and set P is an fatal error
4412    return ($self->bnan()) if defined $a && defined $p; # error
4413
4414    $r = ${"$class\::round_mode"} unless defined $r;
4415    if ($r !~ /^(even|odd|[+-]inf|zero|trunc|common)$/) {
4416        croak("Unknown round mode '$r'");
4417    }
4418
4419    $a = int($a) if defined $a;
4420    $p = int($p) if defined $p;
4421
4422    ($self, $a, $p, $r);
4423}
4424
4425###############################################################################
4426# this method returns 0 if the object can be modified, or 1 if not.
4427# We use a fast constant sub() here, to avoid costly calls. Subclasses
4428# may override it with special code (f.i. Math::BigInt::Constant does so)
4429
4430sub modify () { 0; }
4431
44321;
4433
4434__END__
4435
4436=pod
4437
4438=head1 NAME
4439
4440Math::BigInt - Arbitrary size integer/float math package
4441
4442=head1 SYNOPSIS
4443
4444  use Math::BigInt;
4445
4446  # or make it faster with huge numbers: install (optional)
4447  # Math::BigInt::GMP and always use (it falls back to
4448  # pure Perl if the GMP library is not installed):
4449  # (See also the L<MATH LIBRARY> section!)
4450
4451  # warns if Math::BigInt::GMP cannot be found
4452  use Math::BigInt lib => 'GMP';
4453
4454  # to suppress the warning use this:
4455  # use Math::BigInt try => 'GMP';
4456
4457  # dies if GMP cannot be loaded:
4458  # use Math::BigInt only => 'GMP';
4459
4460  my $str = '1234567890';
4461  my @values = (64, 74, 18);
4462  my $n = 1; my $sign = '-';
4463
4464  # Configuration methods (may be used as class methods and instance methods)
4465
4466  Math::BigInt->accuracy();     # get class accuracy
4467  Math::BigInt->accuracy($n);   # set class accuracy
4468  Math::BigInt->precision();    # get class precision
4469  Math::BigInt->precision($n);  # set class precision
4470  Math::BigInt->round_mode();   # get class rounding mode
4471  Math::BigInt->round_mode($m); # set global round mode, must be one of
4472                                # 'even', 'odd', '+inf', '-inf', 'zero',
4473                                # 'trunc', or 'common'
4474  Math::BigInt->config();       # return hash with configuration
4475
4476  # Constructor methods (when the class methods below are used as instance
4477  # methods, the value is assigned the invocand)
4478
4479  $x = Math::BigInt->new($str);             # defaults to 0
4480  $x = Math::BigInt->new('0x123');          # from hexadecimal
4481  $x = Math::BigInt->new('0b101');          # from binary
4482  $x = Math::BigInt->from_hex('cafe');      # from hexadecimal
4483  $x = Math::BigInt->from_oct('377');       # from octal
4484  $x = Math::BigInt->from_bin('1101');      # from binary
4485  $x = Math::BigInt->from_base('why', 36);  # from any base
4486  $x = Math::BigInt->bzero();               # create a +0
4487  $x = Math::BigInt->bone();                # create a +1
4488  $x = Math::BigInt->bone('-');             # create a -1
4489  $x = Math::BigInt->binf();                # create a +inf
4490  $x = Math::BigInt->binf('-');             # create a -inf
4491  $x = Math::BigInt->bnan();                # create a Not-A-Number
4492  $x = Math::BigInt->bpi();                 # returns pi
4493
4494  $y = $x->copy();         # make a copy (unlike $y = $x)
4495  $y = $x->as_int();       # return as a Math::BigInt
4496
4497  # Boolean methods (these don't modify the invocand)
4498
4499  $x->is_zero();          # if $x is 0
4500  $x->is_one();           # if $x is +1
4501  $x->is_one("+");        # ditto
4502  $x->is_one("-");        # if $x is -1
4503  $x->is_inf();           # if $x is +inf or -inf
4504  $x->is_inf("+");        # if $x is +inf
4505  $x->is_inf("-");        # if $x is -inf
4506  $x->is_nan();           # if $x is NaN
4507
4508  $x->is_positive();      # if $x > 0
4509  $x->is_pos();           # ditto
4510  $x->is_negative();      # if $x < 0
4511  $x->is_neg();           # ditto
4512
4513  $x->is_odd();           # if $x is odd
4514  $x->is_even();          # if $x is even
4515  $x->is_int();           # if $x is an integer
4516
4517  # Comparison methods
4518
4519  $x->bcmp($y);           # compare numbers (undef, < 0, == 0, > 0)
4520  $x->bacmp($y);          # compare absolutely (undef, < 0, == 0, > 0)
4521  $x->beq($y);            # true if and only if $x == $y
4522  $x->bne($y);            # true if and only if $x != $y
4523  $x->blt($y);            # true if and only if $x < $y
4524  $x->ble($y);            # true if and only if $x <= $y
4525  $x->bgt($y);            # true if and only if $x > $y
4526  $x->bge($y);            # true if and only if $x >= $y
4527
4528  # Arithmetic methods
4529
4530  $x->bneg();             # negation
4531  $x->babs();             # absolute value
4532  $x->bsgn();             # sign function (-1, 0, 1, or NaN)
4533  $x->bnorm();            # normalize (no-op)
4534  $x->binc();             # increment $x by 1
4535  $x->bdec();             # decrement $x by 1
4536  $x->badd($y);           # addition (add $y to $x)
4537  $x->bsub($y);           # subtraction (subtract $y from $x)
4538  $x->bmul($y);           # multiplication (multiply $x by $y)
4539  $x->bmuladd($y,$z);     # $x = $x * $y + $z
4540  $x->bdiv($y);           # division (floored), set $x to quotient
4541                          # return (quo,rem) or quo if scalar
4542  $x->btdiv($y);          # division (truncated), set $x to quotient
4543                          # return (quo,rem) or quo if scalar
4544  $x->bmod($y);           # modulus (x % y)
4545  $x->btmod($y);          # modulus (truncated)
4546  $x->bmodinv($mod);      # modular multiplicative inverse
4547  $x->bmodpow($y,$mod);   # modular exponentiation (($x ** $y) % $mod)
4548  $x->bpow($y);           # power of arguments (x ** y)
4549  $x->blog();             # logarithm of $x to base e (Euler's number)
4550  $x->blog($base);        # logarithm of $x to base $base (e.g., base 2)
4551  $x->bexp();             # calculate e ** $x where e is Euler's number
4552  $x->bnok($y);           # x over y (binomial coefficient n over k)
4553  $x->buparrow($n, $y);   # Knuth's up-arrow notation
4554  $x->backermann($y);     # the Ackermann function
4555  $x->bsin();             # sine
4556  $x->bcos();             # cosine
4557  $x->batan();            # inverse tangent
4558  $x->batan2($y);         # two-argument inverse tangent
4559  $x->bsqrt();            # calculate square root
4560  $x->broot($y);          # $y'th root of $x (e.g. $y == 3 => cubic root)
4561  $x->bfac();             # factorial of $x (1*2*3*4*..$x)
4562
4563  $x->blsft($n);          # left shift $n places in base 2
4564  $x->blsft($n,$b);       # left shift $n places in base $b
4565                          # returns (quo,rem) or quo (scalar context)
4566  $x->brsft($n);          # right shift $n places in base 2
4567  $x->brsft($n,$b);       # right shift $n places in base $b
4568                          # returns (quo,rem) or quo (scalar context)
4569
4570  # Bitwise methods
4571
4572  $x->band($y);           # bitwise and
4573  $x->bior($y);           # bitwise inclusive or
4574  $x->bxor($y);           # bitwise exclusive or
4575  $x->bnot();             # bitwise not (two's complement)
4576
4577  # Rounding methods
4578  $x->round($A,$P,$mode); # round to accuracy or precision using
4579                          # rounding mode $mode
4580  $x->bround($n);         # accuracy: preserve $n digits
4581  $x->bfround($n);        # $n > 0: round to $nth digit left of dec. point
4582                          # $n < 0: round to $nth digit right of dec. point
4583  $x->bfloor();           # round towards minus infinity
4584  $x->bceil();            # round towards plus infinity
4585  $x->bint();             # round towards zero
4586
4587  # Other mathematical methods
4588
4589  $x->bgcd($y);            # greatest common divisor
4590  $x->blcm($y);            # least common multiple
4591
4592  # Object property methods (do not modify the invocand)
4593
4594  $x->sign();              # the sign, either +, - or NaN
4595  $x->digit($n);           # the nth digit, counting from the right
4596  $x->digit(-$n);          # the nth digit, counting from the left
4597  $x->length();            # return number of digits in number
4598  ($xl,$f) = $x->length(); # length of number and length of fraction
4599                           # part, latter is always 0 digits long
4600                           # for Math::BigInt objects
4601  $x->mantissa();          # return (signed) mantissa as a Math::BigInt
4602  $x->exponent();          # return exponent as a Math::BigInt
4603  $x->parts();             # return (mantissa,exponent) as a Math::BigInt
4604  $x->sparts();            # mantissa and exponent (as integers)
4605  $x->nparts();            # mantissa and exponent (normalised)
4606  $x->eparts();            # mantissa and exponent (engineering notation)
4607  $x->dparts();            # integer and fraction part
4608
4609  # Conversion methods (do not modify the invocand)
4610
4611  $x->bstr();         # decimal notation, possibly zero padded
4612  $x->bsstr();        # string in scientific notation with integers
4613  $x->bnstr();        # string in normalized notation
4614  $x->bestr();        # string in engineering notation
4615  $x->bdstr();        # string in decimal notation
4616
4617  $x->to_hex();       # as signed hexadecimal string
4618  $x->to_bin();       # as signed binary string
4619  $x->to_oct();       # as signed octal string
4620  $x->to_bytes();     # as byte string
4621  $x->to_base($b);    # as string in any base
4622
4623  $x->as_hex();       # as signed hexadecimal string with prefixed 0x
4624  $x->as_bin();       # as signed binary string with prefixed 0b
4625  $x->as_oct();       # as signed octal string with prefixed 0
4626
4627  # Other conversion methods
4628
4629  $x->numify();           # return as scalar (might overflow or underflow)
4630
4631=head1 DESCRIPTION
4632
4633Math::BigInt provides support for arbitrary precision integers. Overloading is
4634also provided for Perl operators.
4635
4636=head2 Input
4637
4638Input values to these routines may be any scalar number or string that looks
4639like a number and represents an integer.
4640
4641=over
4642
4643=item *
4644
4645Leading and trailing whitespace is ignored.
4646
4647=item *
4648
4649Leading and trailing zeros are ignored.
4650
4651=item *
4652
4653If the string has a "0x" prefix, it is interpreted as a hexadecimal number.
4654
4655=item *
4656
4657If the string has a "0b" prefix, it is interpreted as a binary number.
4658
4659=item *
4660
4661One underline is allowed between any two digits.
4662
4663=item *
4664
4665If the string can not be interpreted, NaN is returned.
4666
4667=back
4668
4669Octal numbers are typically prefixed by "0", but since leading zeros are
4670stripped, these methods can not automatically recognize octal numbers, so use
4671the constructor from_oct() to interpret octal strings.
4672
4673Some examples of valid string input
4674
4675    Input string                Resulting value
4676    123                         123
4677    1.23e2                      123
4678    12300e-2                    123
4679    0xcafe                      51966
4680    0b1101                      13
4681    67_538_754                  67538754
4682    -4_5_6.7_8_9e+0_1_0         -4567890000000
4683
4684Input given as scalar numbers might lose precision. Quote your input to ensure
4685that no digits are lost:
4686
4687    $x = Math::BigInt->new( 56789012345678901234 );   # bad
4688    $x = Math::BigInt->new('56789012345678901234');   # good
4689
4690Currently, Math::BigInt->new() defaults to 0, while Math::BigInt->new('')
4691results in 'NaN'. This might change in the future, so use always the following
4692explicit forms to get a zero or NaN:
4693
4694    $zero = Math::BigInt->bzero();
4695    $nan  = Math::BigInt->bnan();
4696
4697=head2 Output
4698
4699Output values are usually Math::BigInt objects.
4700
4701Boolean operators C<is_zero()>, C<is_one()>, C<is_inf()>, etc. return true or
4702false.
4703
4704Comparison operators C<bcmp()> and C<bacmp()>) return -1, 0, 1, or
4705undef.
4706
4707=head1 METHODS
4708
4709=head2 Configuration methods
4710
4711Each of the methods below (except config(), accuracy() and precision()) accepts
4712three additional parameters. These arguments C<$A>, C<$P> and C<$R> are
4713C<accuracy>, C<precision> and C<round_mode>. Please see the section about
4714L</ACCURACY and PRECISION> for more information.
4715
4716Setting a class variable effects all object instance that are created
4717afterwards.
4718
4719=over
4720
4721=item accuracy()
4722
4723    Math::BigInt->accuracy(5);      # set class accuracy
4724    $x->accuracy(5);                # set instance accuracy
4725
4726    $A = Math::BigInt->accuracy();  # get class accuracy
4727    $A = $x->accuracy();            # get instance accuracy
4728
4729Set or get the accuracy, i.e., the number of significant digits. The accuracy
4730must be an integer. If the accuracy is set to C<undef>, no rounding is done.
4731
4732Alternatively, one can round the results explicitly using one of L</round()>,
4733L</bround()> or L</bfround()> or by passing the desired accuracy to the method
4734as an additional parameter:
4735
4736    my $x = Math::BigInt->new(30000);
4737    my $y = Math::BigInt->new(7);
4738    print scalar $x->copy()->bdiv($y, 2);               # prints 4300
4739    print scalar $x->copy()->bdiv($y)->bround(2);       # prints 4300
4740
4741Please see the section about L</ACCURACY and PRECISION> for further details.
4742
4743    $y = Math::BigInt->new(1234567);    # $y is not rounded
4744    Math::BigInt->accuracy(4);          # set class accuracy to 4
4745    $x = Math::BigInt->new(1234567);    # $x is rounded automatically
4746    print "$x $y";                      # prints "1235000 1234567"
4747
4748    print $x->accuracy();       # prints "4"
4749    print $y->accuracy();       # also prints "4", since
4750                                #   class accuracy is 4
4751
4752    Math::BigInt->accuracy(5);  # set class accuracy to 5
4753    print $x->accuracy();       # prints "4", since instance
4754                                #   accuracy is 4
4755    print $y->accuracy();       # prints "5", since no instance
4756                                #   accuracy, and class accuracy is 5
4757
4758Note: Each class has it's own globals separated from Math::BigInt, but it is
4759possible to subclass Math::BigInt and make the globals of the subclass aliases
4760to the ones from Math::BigInt.
4761
4762=item precision()
4763
4764    Math::BigInt->precision(-2);     # set class precision
4765    $x->precision(-2);               # set instance precision
4766
4767    $P = Math::BigInt->precision();  # get class precision
4768    $P = $x->precision();            # get instance precision
4769
4770Set or get the precision, i.e., the place to round relative to the decimal
4771point. The precision must be a integer. Setting the precision to $P means that
4772each number is rounded up or down, depending on the rounding mode, to the
4773nearest multiple of 10**$P. If the precision is set to C<undef>, no rounding is
4774done.
4775
4776You might want to use L</accuracy()> instead. With L</accuracy()> you set the
4777number of digits each result should have, with L</precision()> you set the
4778place where to round.
4779
4780Please see the section about L</ACCURACY and PRECISION> for further details.
4781
4782    $y = Math::BigInt->new(1234567);    # $y is not rounded
4783    Math::BigInt->precision(4);         # set class precision to 4
4784    $x = Math::BigInt->new(1234567);    # $x is rounded automatically
4785    print $x;                           # prints "1230000"
4786
4787Note: Each class has its own globals separated from Math::BigInt, but it is
4788possible to subclass Math::BigInt and make the globals of the subclass aliases
4789to the ones from Math::BigInt.
4790
4791=item div_scale()
4792
4793Set/get the fallback accuracy. This is the accuracy used when neither accuracy
4794nor precision is set explicitly. It is used when a computation might otherwise
4795attempt to return an infinite number of digits.
4796
4797=item round_mode()
4798
4799Set/get the rounding mode.
4800
4801=item upgrade()
4802
4803Set/get the class for upgrading. When a computation might result in a
4804non-integer, the operands are upgraded to this class. This is used for instance
4805by L<bignum>. The default is C<undef>, thus the following operation creates
4806a Math::BigInt, not a Math::BigFloat:
4807
4808    my $i = Math::BigInt->new(123);
4809    my $f = Math::BigFloat->new('123.1');
4810
4811    print $i + $f, "\n";                # prints 246
4812
4813=item downgrade()
4814
4815Set/get the class for downgrading. The default is C<undef>. Downgrading is not
4816done by Math::BigInt.
4817
4818=item modify()
4819
4820    $x->modify('bpowd');
4821
4822This method returns 0 if the object can be modified with the given operation,
4823or 1 if not.
4824
4825This is used for instance by L<Math::BigInt::Constant>.
4826
4827=item config()
4828
4829    Math::BigInt->config("trap_nan" => 1);      # set
4830    $accu = Math::BigInt->config("accuracy");   # get
4831
4832Set or get class variables. Read-only parameters are marked as RO. Read-write
4833parameters are marked as RW. The following parameters are supported.
4834
4835    Parameter       RO/RW   Description
4836                            Example
4837    ============================================================
4838    lib             RO      Name of the math backend library
4839                            Math::BigInt::Calc
4840    lib_version     RO      Version of the math backend library
4841                            0.30
4842    class           RO      The class of config you just called
4843                            Math::BigRat
4844    version         RO      version number of the class you used
4845                            0.10
4846    upgrade         RW      To which class numbers are upgraded
4847                            undef
4848    downgrade       RW      To which class numbers are downgraded
4849                            undef
4850    precision       RW      Global precision
4851                            undef
4852    accuracy        RW      Global accuracy
4853                            undef
4854    round_mode      RW      Global round mode
4855                            even
4856    div_scale       RW      Fallback accuracy for division etc.
4857                            40
4858    trap_nan        RW      Trap NaNs
4859                            undef
4860    trap_inf        RW      Trap +inf/-inf
4861                            undef
4862
4863=back
4864
4865=head2 Constructor methods
4866
4867=over
4868
4869=item new()
4870
4871    $x = Math::BigInt->new($str,$A,$P,$R);
4872
4873Creates a new Math::BigInt object from a scalar or another Math::BigInt object.
4874The input is accepted as decimal, hexadecimal (with leading '0x') or binary
4875(with leading '0b').
4876
4877See L</Input> for more info on accepted input formats.
4878
4879=item from_hex()
4880
4881    $x = Math::BigInt->from_hex("0xcafe");    # input is hexadecimal
4882
4883Interpret input as a hexadecimal string. A "0x" or "x" prefix is optional. A
4884single underscore character may be placed right after the prefix, if present,
4885or between any two digits. If the input is invalid, a NaN is returned.
4886
4887=item from_oct()
4888
4889    $x = Math::BigInt->from_oct("0775");      # input is octal
4890
4891Interpret the input as an octal string and return the corresponding value. A
4892"0" (zero) prefix is optional. A single underscore character may be placed
4893right after the prefix, if present, or between any two digits. If the input is
4894invalid, a NaN is returned.
4895
4896=item from_bin()
4897
4898    $x = Math::BigInt->from_bin("0b10011");   # input is binary
4899
4900Interpret the input as a binary string. A "0b" or "b" prefix is optional. A
4901single underscore character may be placed right after the prefix, if present,
4902or between any two digits. If the input is invalid, a NaN is returned.
4903
4904=item from_bytes()
4905
4906    $x = Math::BigInt->from_bytes("\xf3\x6b");  # $x = 62315
4907
4908Interpret the input as a byte string, assuming big endian byte order. The
4909output is always a non-negative, finite integer.
4910
4911In some special cases, from_bytes() matches the conversion done by unpack():
4912
4913    $b = "\x4e";                             # one char byte string
4914    $x = Math::BigInt->from_bytes($b);       # = 78
4915    $y = unpack "C", $b;                     # ditto, but scalar
4916
4917    $b = "\xf3\x6b";                         # two char byte string
4918    $x = Math::BigInt->from_bytes($b);       # = 62315
4919    $y = unpack "S>", $b;                    # ditto, but scalar
4920
4921    $b = "\x2d\xe0\x49\xad";                 # four char byte string
4922    $x = Math::BigInt->from_bytes($b);       # = 769673645
4923    $y = unpack "L>", $b;                    # ditto, but scalar
4924
4925    $b = "\x2d\xe0\x49\xad\x2d\xe0\x49\xad"; # eight char byte string
4926    $x = Math::BigInt->from_bytes($b);       # = 3305723134637787565
4927    $y = unpack "Q>", $b;                    # ditto, but scalar
4928
4929=item from_base()
4930
4931Given a string, a base, and an optional collation sequence, interpret the
4932string as a number in the given base. The collation sequence describes the
4933value of each character in the string.
4934
4935If a collation sequence is not given, a default collation sequence is used. If
4936the base is less than or equal to 36, the collation sequence is the string
4937consisting of the 36 characters "0" to "9" and "A" to "Z". In this case, the
4938letter case in the input is ignored. If the base is greater than 36, and
4939smaller than or equal to 62, the collation sequence is the string consisting of
4940the 62 characters "0" to "9", "A" to "Z", and "a" to "z". A base larger than 62
4941requires the collation sequence to be specified explicitly.
4942
4943These examples show standard binary, octal, and hexadecimal conversion. All
4944cases return 250.
4945
4946    $x = Math::BigInt->from_base("11111010", 2);
4947    $x = Math::BigInt->from_base("372", 8);
4948    $x = Math::BigInt->from_base("fa", 16);
4949
4950When the base is less than or equal to 36, and no collation sequence is given,
4951the letter case is ignored, so both of these also return 250:
4952
4953    $x = Math::BigInt->from_base("6Y", 16);
4954    $x = Math::BigInt->from_base("6y", 16);
4955
4956When the base greater than 36, and no collation sequence is given, the default
4957collation sequence contains both uppercase and lowercase letters, so
4958the letter case in the input is not ignored:
4959
4960    $x = Math::BigInt->from_base("6S", 37);         # $x is 250
4961    $x = Math::BigInt->from_base("6s", 37);         # $x is 276
4962    $x = Math::BigInt->from_base("121", 3);         # $x is 16
4963    $x = Math::BigInt->from_base("XYZ", 36);        # $x is 44027
4964    $x = Math::BigInt->from_base("Why", 42);        # $x is 58314
4965
4966The collation sequence can be any set of unique characters. These two cases
4967are equivalent
4968
4969    $x = Math::BigInt->from_base("100", 2, "01");   # $x is 4
4970    $x = Math::BigInt->from_base("|--", 2, "-|");   # $x is 4
4971
4972=item bzero()
4973
4974    $x = Math::BigInt->bzero();
4975    $x->bzero();
4976
4977Returns a new Math::BigInt object representing zero. If used as an instance
4978method, assigns the value to the invocand.
4979
4980=item bone()
4981
4982    $x = Math::BigInt->bone();          # +1
4983    $x = Math::BigInt->bone("+");       # +1
4984    $x = Math::BigInt->bone("-");       # -1
4985    $x->bone();                         # +1
4986    $x->bone("+");                      # +1
4987    $x->bone('-');                      # -1
4988
4989Creates a new Math::BigInt object representing one. The optional argument is
4990either '-' or '+', indicating whether you want plus one or minus one. If used
4991as an instance method, assigns the value to the invocand.
4992
4993=item binf()
4994
4995    $x = Math::BigInt->binf($sign);
4996
4997Creates a new Math::BigInt object representing infinity. The optional argument
4998is either '-' or '+', indicating whether you want infinity or minus infinity.
4999If used as an instance method, assigns the value to the invocand.
5000
5001    $x->binf();
5002    $x->binf('-');
5003
5004=item bnan()
5005
5006    $x = Math::BigInt->bnan();
5007
5008Creates a new Math::BigInt object representing NaN (Not A Number). If used as
5009an instance method, assigns the value to the invocand.
5010
5011    $x->bnan();
5012
5013=item bpi()
5014
5015    $x = Math::BigInt->bpi(100);        # 3
5016    $x->bpi(100);                       # 3
5017
5018Creates a new Math::BigInt object representing PI. If used as an instance
5019method, assigns the value to the invocand. With Math::BigInt this always
5020returns 3.
5021
5022If upgrading is in effect, returns PI, rounded to N digits with the current
5023rounding mode:
5024
5025    use Math::BigFloat;
5026    use Math::BigInt upgrade => "Math::BigFloat";
5027    print Math::BigInt->bpi(3), "\n";           # 3.14
5028    print Math::BigInt->bpi(100), "\n";         # 3.1415....
5029
5030=item copy()
5031
5032    $x->copy();         # make a true copy of $x (unlike $y = $x)
5033
5034=item as_int()
5035
5036=item as_number()
5037
5038These methods are called when Math::BigInt encounters an object it doesn't know
5039how to handle. For instance, assume $x is a Math::BigInt, or subclass thereof,
5040and $y is defined, but not a Math::BigInt, or subclass thereof. If you do
5041
5042    $x -> badd($y);
5043
5044$y needs to be converted into an object that $x can deal with. This is done by
5045first checking if $y is something that $x might be upgraded to. If that is the
5046case, no further attempts are made. The next is to see if $y supports the
5047method C<as_int()>. If it does, C<as_int()> is called, but if it doesn't, the
5048next thing is to see if $y supports the method C<as_number()>. If it does,
5049C<as_number()> is called. The method C<as_int()> (and C<as_number()>) is
5050expected to return either an object that has the same class as $x, a subclass
5051thereof, or a string that C<ref($x)-E<gt>new()> can parse to create an object.
5052
5053C<as_number()> is an alias to C<as_int()>. C<as_number> was introduced in
5054v1.22, while C<as_int()> was introduced in v1.68.
5055
5056In Math::BigInt, C<as_int()> has the same effect as C<copy()>.
5057
5058=back
5059
5060=head2 Boolean methods
5061
5062None of these methods modify the invocand object.
5063
5064=over
5065
5066=item is_zero()
5067
5068    $x->is_zero();              # true if $x is 0
5069
5070Returns true if the invocand is zero and false otherwise.
5071
5072=item is_one( [ SIGN ])
5073
5074    $x->is_one();               # true if $x is +1
5075    $x->is_one("+");            # ditto
5076    $x->is_one("-");            # true if $x is -1
5077
5078Returns true if the invocand is one and false otherwise.
5079
5080=item is_finite()
5081
5082    $x->is_finite();    # true if $x is not +inf, -inf or NaN
5083
5084Returns true if the invocand is a finite number, i.e., it is neither +inf,
5085-inf, nor NaN.
5086
5087=item is_inf( [ SIGN ] )
5088
5089    $x->is_inf();               # true if $x is +inf
5090    $x->is_inf("+");            # ditto
5091    $x->is_inf("-");            # true if $x is -inf
5092
5093Returns true if the invocand is infinite and false otherwise.
5094
5095=item is_nan()
5096
5097    $x->is_nan();               # true if $x is NaN
5098
5099=item is_positive()
5100
5101=item is_pos()
5102
5103    $x->is_positive();          # true if > 0
5104    $x->is_pos();               # ditto
5105
5106Returns true if the invocand is positive and false otherwise. A C<NaN> is
5107neither positive nor negative.
5108
5109=item is_negative()
5110
5111=item is_neg()
5112
5113    $x->is_negative();          # true if < 0
5114    $x->is_neg();               # ditto
5115
5116Returns true if the invocand is negative and false otherwise. A C<NaN> is
5117neither positive nor negative.
5118
5119=item is_non_positive()
5120
5121    $x->is_non_positive();      # true if <= 0
5122
5123Returns true if the invocand is negative or zero.
5124
5125=item is_non_negative()
5126
5127    $x->is_non_negative();      # true if >= 0
5128
5129Returns true if the invocand is positive or zero.
5130
5131=item is_odd()
5132
5133    $x->is_odd();               # true if odd, false for even
5134
5135Returns true if the invocand is odd and false otherwise. C<NaN>, C<+inf>, and
5136C<-inf> are neither odd nor even.
5137
5138=item is_even()
5139
5140    $x->is_even();              # true if $x is even
5141
5142Returns true if the invocand is even and false otherwise. C<NaN>, C<+inf>,
5143C<-inf> are not integers and are neither odd nor even.
5144
5145=item is_int()
5146
5147    $x->is_int();               # true if $x is an integer
5148
5149Returns true if the invocand is an integer and false otherwise. C<NaN>,
5150C<+inf>, C<-inf> are not integers.
5151
5152=back
5153
5154=head2 Comparison methods
5155
5156None of these methods modify the invocand object. Note that a C<NaN> is neither
5157less than, greater than, or equal to anything else, even a C<NaN>.
5158
5159=over
5160
5161=item bcmp()
5162
5163    $x->bcmp($y);
5164
5165Returns -1, 0, 1 depending on whether $x is less than, equal to, or grater than
5166$y. Returns undef if any operand is a NaN.
5167
5168=item bacmp()
5169
5170    $x->bacmp($y);
5171
5172Returns -1, 0, 1 depending on whether the absolute value of $x is less than,
5173equal to, or grater than the absolute value of $y. Returns undef if any operand
5174is a NaN.
5175
5176=item beq()
5177
5178    $x -> beq($y);
5179
5180Returns true if and only if $x is equal to $y, and false otherwise.
5181
5182=item bne()
5183
5184    $x -> bne($y);
5185
5186Returns true if and only if $x is not equal to $y, and false otherwise.
5187
5188=item blt()
5189
5190    $x -> blt($y);
5191
5192Returns true if and only if $x is equal to $y, and false otherwise.
5193
5194=item ble()
5195
5196    $x -> ble($y);
5197
5198Returns true if and only if $x is less than or equal to $y, and false
5199otherwise.
5200
5201=item bgt()
5202
5203    $x -> bgt($y);
5204
5205Returns true if and only if $x is greater than $y, and false otherwise.
5206
5207=item bge()
5208
5209    $x -> bge($y);
5210
5211Returns true if and only if $x is greater than or equal to $y, and false
5212otherwise.
5213
5214=back
5215
5216=head2 Arithmetic methods
5217
5218These methods modify the invocand object and returns it.
5219
5220=over
5221
5222=item bneg()
5223
5224    $x->bneg();
5225
5226Negate the number, e.g. change the sign between '+' and '-', or between '+inf'
5227and '-inf', respectively. Does nothing for NaN or zero.
5228
5229=item babs()
5230
5231    $x->babs();
5232
5233Set the number to its absolute value, e.g. change the sign from '-' to '+'
5234and from '-inf' to '+inf', respectively. Does nothing for NaN or positive
5235numbers.
5236
5237=item bsgn()
5238
5239    $x->bsgn();
5240
5241Signum function. Set the number to -1, 0, or 1, depending on whether the
5242number is negative, zero, or positive, respectively. Does not modify NaNs.
5243
5244=item bnorm()
5245
5246    $x->bnorm();                        # normalize (no-op)
5247
5248Normalize the number. This is a no-op and is provided only for backwards
5249compatibility.
5250
5251=item binc()
5252
5253    $x->binc();                 # increment x by 1
5254
5255=item bdec()
5256
5257    $x->bdec();                 # decrement x by 1
5258
5259=item badd()
5260
5261    $x->badd($y);               # addition (add $y to $x)
5262
5263=item bsub()
5264
5265    $x->bsub($y);               # subtraction (subtract $y from $x)
5266
5267=item bmul()
5268
5269    $x->bmul($y);               # multiplication (multiply $x by $y)
5270
5271=item bmuladd()
5272
5273    $x->bmuladd($y,$z);
5274
5275Multiply $x by $y, and then add $z to the result,
5276
5277This method was added in v1.87 of Math::BigInt (June 2007).
5278
5279=item bdiv()
5280
5281    $x->bdiv($y);               # divide, set $x to quotient
5282
5283Divides $x by $y by doing floored division (F-division), where the quotient is
5284the floored (rounded towards negative infinity) quotient of the two operands.
5285In list context, returns the quotient and the remainder. The remainder is
5286either zero or has the same sign as the second operand. In scalar context, only
5287the quotient is returned.
5288
5289The quotient is always the greatest integer less than or equal to the
5290real-valued quotient of the two operands, and the remainder (when it is
5291non-zero) always has the same sign as the second operand; so, for example,
5292
5293      1 /  4  => ( 0,  1)
5294      1 / -4  => (-1, -3)
5295     -3 /  4  => (-1,  1)
5296     -3 / -4  => ( 0, -3)
5297    -11 /  2  => (-5,  1)
5298     11 / -2  => (-5, -1)
5299
5300The behavior of the overloaded operator % agrees with the behavior of Perl's
5301built-in % operator (as documented in the perlop manpage), and the equation
5302
5303    $x == ($x / $y) * $y + ($x % $y)
5304
5305holds true for any finite $x and finite, non-zero $y.
5306
5307Perl's "use integer" might change the behaviour of % and / for scalars. This is
5308because under 'use integer' Perl does what the underlying C library thinks is
5309right, and this varies. However, "use integer" does not change the way things
5310are done with Math::BigInt objects.
5311
5312=item btdiv()
5313
5314    $x->btdiv($y);              # divide, set $x to quotient
5315
5316Divides $x by $y by doing truncated division (T-division), where quotient is
5317the truncated (rouneded towards zero) quotient of the two operands. In list
5318context, returns the quotient and the remainder. The remainder is either zero
5319or has the same sign as the first operand. In scalar context, only the quotient
5320is returned.
5321
5322=item bmod()
5323
5324    $x->bmod($y);               # modulus (x % y)
5325
5326Returns $x modulo $y, i.e., the remainder after floored division (F-division).
5327This method is like Perl's % operator. See L</bdiv()>.
5328
5329=item btmod()
5330
5331    $x->btmod($y);              # modulus
5332
5333Returns the remainer after truncated division (T-division). See L</btdiv()>.
5334
5335=item bmodinv()
5336
5337    $x->bmodinv($mod);          # modular multiplicative inverse
5338
5339Returns the multiplicative inverse of C<$x> modulo C<$mod>. If
5340
5341    $y = $x -> copy() -> bmodinv($mod)
5342
5343then C<$y> is the number closest to zero, and with the same sign as C<$mod>,
5344satisfying
5345
5346    ($x * $y) % $mod = 1 % $mod
5347
5348If C<$x> and C<$y> are non-zero, they must be relative primes, i.e.,
5349C<bgcd($y, $mod)==1>. 'C<NaN>' is returned when no modular multiplicative
5350inverse exists.
5351
5352=item bmodpow()
5353
5354    $num->bmodpow($exp,$mod);           # modular exponentiation
5355                                        # ($num**$exp % $mod)
5356
5357Returns the value of C<$num> taken to the power C<$exp> in the modulus
5358C<$mod> using binary exponentiation.  C<bmodpow> is far superior to
5359writing
5360
5361    $num ** $exp % $mod
5362
5363because it is much faster - it reduces internal variables into
5364the modulus whenever possible, so it operates on smaller numbers.
5365
5366C<bmodpow> also supports negative exponents.
5367
5368    bmodpow($num, -1, $mod)
5369
5370is exactly equivalent to
5371
5372    bmodinv($num, $mod)
5373
5374=item bpow()
5375
5376    $x->bpow($y);               # power of arguments (x ** y)
5377
5378C<bpow()> (and the rounding functions) now modifies the first argument and
5379returns it, unlike the old code which left it alone and only returned the
5380result. This is to be consistent with C<badd()> etc. The first three modifies
5381$x, the last one won't:
5382
5383    print bpow($x,$i),"\n";         # modify $x
5384    print $x->bpow($i),"\n";        # ditto
5385    print $x **= $i,"\n";           # the same
5386    print $x ** $i,"\n";            # leave $x alone
5387
5388The form C<$x **= $y> is faster than C<$x = $x ** $y;>, though.
5389
5390=item blog()
5391
5392    $x->blog($base, $accuracy);         # logarithm of x to the base $base
5393
5394If C<$base> is not defined, Euler's number (e) is used:
5395
5396    print $x->blog(undef, 100);         # log(x) to 100 digits
5397
5398=item bexp()
5399
5400    $x->bexp($accuracy);                # calculate e ** X
5401
5402Calculates the expression C<e ** $x> where C<e> is Euler's number.
5403
5404This method was added in v1.82 of Math::BigInt (April 2007).
5405
5406See also L</blog()>.
5407
5408=item bnok()
5409
5410    $x->bnok($y);               # x over y (binomial coefficient n over k)
5411
5412Calculates the binomial coefficient n over k, also called the "choose"
5413function, which is
5414
5415    ( n )       n!
5416    |   |  = --------
5417    ( k )    k!(n-k)!
5418
5419when n and k are non-negative. This method implements the full Kronenburg
5420extension (Kronenburg, M.J. "The Binomial Coefficient for Negative Arguments."
542118 May 2011. http://arxiv.org/abs/1105.3689/) illustrated by the following
5422pseudo-code:
5423
5424    if n >= 0 and k >= 0:
5425        return binomial(n, k)
5426    if k >= 0:
5427        return (-1)^k*binomial(-n+k-1, k)
5428    if k <= n:
5429        return (-1)^(n-k)*binomial(-k-1, n-k)
5430    else
5431        return 0
5432
5433The behaviour is identical to the behaviour of the Maple and Mathematica
5434function for negative integers n, k.
5435
5436=item buparrow()
5437
5438=item uparrow()
5439
5440    $a -> buparrow($n, $b);         # modifies $a
5441    $x = $a -> uparrow($n, $b);     # does not modify $a
5442
5443This method implements Knuth's up-arrow notation, where $n is a non-negative
5444integer representing the number of up-arrows. $n = 0 gives multiplication, $n =
54451 gives exponentiation, $n = 2 gives tetration, $n = 3 gives hexation etc. The
5446following illustrates the relation between the first values of $n.
5447
5448See L<https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation>.
5449
5450=item backermann()
5451
5452=item ackermann()
5453
5454    $m -> backermann($n);           # modifies $a
5455    $x = $m -> ackermann($n);       # does not modify $a
5456
5457This method implements the Ackermann function:
5458
5459             / n + 1              if m = 0
5460   A(m, n) = | A(m-1, 1)          if m > 0 and n = 0
5461             \ A(m-1, A(m, n-1))  if m > 0 and n > 0
5462
5463Its value grows rapidly, even for small inputs. For example, A(4, 2) is an
5464integer of 19729 decimal digits.
5465
5466See https://en.wikipedia.org/wiki/Ackermann_function
5467
5468=item bsin()
5469
5470    my $x = Math::BigInt->new(1);
5471    print $x->bsin(100), "\n";
5472
5473Calculate the sine of $x, modifying $x in place.
5474
5475In Math::BigInt, unless upgrading is in effect, the result is truncated to an
5476integer.
5477
5478This method was added in v1.87 of Math::BigInt (June 2007).
5479
5480=item bcos()
5481
5482    my $x = Math::BigInt->new(1);
5483    print $x->bcos(100), "\n";
5484
5485Calculate the cosine of $x, modifying $x in place.
5486
5487In Math::BigInt, unless upgrading is in effect, the result is truncated to an
5488integer.
5489
5490This method was added in v1.87 of Math::BigInt (June 2007).
5491
5492=item batan()
5493
5494    my $x = Math::BigFloat->new(0.5);
5495    print $x->batan(100), "\n";
5496
5497Calculate the arcus tangens of $x, modifying $x in place.
5498
5499In Math::BigInt, unless upgrading is in effect, the result is truncated to an
5500integer.
5501
5502This method was added in v1.87 of Math::BigInt (June 2007).
5503
5504=item batan2()
5505
5506    my $x = Math::BigInt->new(1);
5507    my $y = Math::BigInt->new(1);
5508    print $y->batan2($x), "\n";
5509
5510Calculate the arcus tangens of C<$y> divided by C<$x>, modifying $y in place.
5511
5512In Math::BigInt, unless upgrading is in effect, the result is truncated to an
5513integer.
5514
5515This method was added in v1.87 of Math::BigInt (June 2007).
5516
5517=item bsqrt()
5518
5519    $x->bsqrt();                # calculate square root
5520
5521C<bsqrt()> returns the square root truncated to an integer.
5522
5523If you want a better approximation of the square root, then use:
5524
5525    $x = Math::BigFloat->new(12);
5526    Math::BigFloat->precision(0);
5527    Math::BigFloat->round_mode('even');
5528    print $x->copy->bsqrt(),"\n";           # 4
5529
5530    Math::BigFloat->precision(2);
5531    print $x->bsqrt(),"\n";                 # 3.46
5532    print $x->bsqrt(3),"\n";                # 3.464
5533
5534=item broot()
5535
5536    $x->broot($N);
5537
5538Calculates the N'th root of C<$x>.
5539
5540=item bfac()
5541
5542    $x->bfac();                 # factorial of $x (1*2*3*4*..*$x)
5543
5544Returns the factorial of C<$x>, i.e., the product of all positive integers up
5545to and including C<$x>.
5546
5547=item bdfac()
5548
5549    $x->bdfac();                # double factorial of $x (1*2*3*4*..*$x)
5550
5551Returns the double factorial of C<$x>. If C<$x> is an even integer, returns the
5552product of all positive, even integers up to and including C<$x>, i.e.,
55532*4*6*...*$x. If C<$x> is an odd integer, returns the product of all positive,
5554odd integers, i.e., 1*3*5*...*$x.
5555
5556=item bfib()
5557
5558    $F = $n->bfib();            # a single Fibonacci number
5559    @F = $n->bfib();            # a list of Fibonacci numbers
5560
5561In scalar context, returns a single Fibonacci number. In list context, returns
5562a list of Fibonacci numbers. The invocand is the last element in the output.
5563
5564The Fibonacci sequence is defined by
5565
5566    F(0) = 0
5567    F(1) = 1
5568    F(n) = F(n-1) + F(n-2)
5569
5570In list context, F(0) and F(n) is the first and last number in the output,
5571respectively. For example, if $n is 12, then C<< @F = $n->bfib() >> returns the
5572following values, F(0) to F(12):
5573
5574    0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
5575
5576The sequence can also be extended to negative index n using the re-arranged
5577recurrence relation
5578
5579    F(n-2) = F(n) - F(n-1)
5580
5581giving the bidirectional sequence
5582
5583       n  -7  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5   6   7
5584    F(n)  13  -8   5  -3   2  -1   1   0   1   1   2   3   5   8  13
5585
5586If $n is -12, the following values, F(0) to F(12), are returned:
5587
5588    0, 1, -1, 2, -3, 5, -8, 13, -21, 34, -55, 89, -144
5589
5590=item blucas()
5591
5592    $F = $n->blucas();          # a single Lucas number
5593    @F = $n->blucas();          # a list of Lucas numbers
5594
5595In scalar context, returns a single Lucas number. In list context, returns a
5596list of Lucas numbers. The invocand is the last element in the output.
5597
5598The Lucas sequence is defined by
5599
5600    L(0) = 2
5601    L(1) = 1
5602    L(n) = L(n-1) + L(n-2)
5603
5604In list context, L(0) and L(n) is the first and last number in the output,
5605respectively. For example, if $n is 12, then C<< @L = $n->blucas() >> returns
5606the following values, L(0) to L(12):
5607
5608    2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322
5609
5610The sequence can also be extended to negative index n using the re-arranged
5611recurrence relation
5612
5613    L(n-2) = L(n) - L(n-1)
5614
5615giving the bidirectional sequence
5616
5617       n  -7  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5   6   7
5618    L(n)  29 -18  11  -7   4  -3   1   2   1   3   4   7  11  18  29
5619
5620If $n is -12, the following values, L(0) to L(-12), are returned:
5621
5622    2, 1, -3, 4, -7, 11, -18, 29, -47, 76, -123, 199, -322
5623
5624=item brsft()
5625
5626    $x->brsft($n);              # right shift $n places in base 2
5627    $x->brsft($n, $b);          # right shift $n places in base $b
5628
5629The latter is equivalent to
5630
5631    $x -> bdiv($b -> copy() -> bpow($n))
5632
5633=item blsft()
5634
5635    $x->blsft($n);              # left shift $n places in base 2
5636    $x->blsft($n, $b);          # left shift $n places in base $b
5637
5638The latter is equivalent to
5639
5640    $x -> bmul($b -> copy() -> bpow($n))
5641
5642=back
5643
5644=head2 Bitwise methods
5645
5646=over
5647
5648=item band()
5649
5650    $x->band($y);               # bitwise and
5651
5652=item bior()
5653
5654    $x->bior($y);               # bitwise inclusive or
5655
5656=item bxor()
5657
5658    $x->bxor($y);               # bitwise exclusive or
5659
5660=item bnot()
5661
5662    $x->bnot();                 # bitwise not (two's complement)
5663
5664Two's complement (bitwise not). This is equivalent to, but faster than,
5665
5666    $x->binc()->bneg();
5667
5668=back
5669
5670=head2 Rounding methods
5671
5672=over
5673
5674=item round()
5675
5676    $x->round($A,$P,$round_mode);
5677
5678Round $x to accuracy C<$A> or precision C<$P> using the round mode
5679C<$round_mode>.
5680
5681=item bround()
5682
5683    $x->bround($N);               # accuracy: preserve $N digits
5684
5685Rounds $x to an accuracy of $N digits.
5686
5687=item bfround()
5688
5689    $x->bfround($N);
5690
5691Rounds to a multiple of 10**$N. Examples:
5692
5693    Input            N          Result
5694
5695    123456.123456    3          123500
5696    123456.123456    2          123450
5697    123456.123456   -2          123456.12
5698    123456.123456   -3          123456.123
5699
5700=item bfloor()
5701
5702    $x->bfloor();
5703
5704Round $x towards minus infinity, i.e., set $x to the largest integer less than
5705or equal to $x.
5706
5707=item bceil()
5708
5709    $x->bceil();
5710
5711Round $x towards plus infinity, i.e., set $x to the smallest integer greater
5712than or equal to $x).
5713
5714=item bint()
5715
5716    $x->bint();
5717
5718Round $x towards zero.
5719
5720=back
5721
5722=head2 Other mathematical methods
5723
5724=over
5725
5726=item bgcd()
5727
5728    $x -> bgcd($y);             # GCD of $x and $y
5729    $x -> bgcd($y, $z, ...);    # GCD of $x, $y, $z, ...
5730
5731Returns the greatest common divisor (GCD).
5732
5733=item blcm()
5734
5735    $x -> blcm($y);             # LCM of $x and $y
5736    $x -> blcm($y, $z, ...);    # LCM of $x, $y, $z, ...
5737
5738Returns the least common multiple (LCM).
5739
5740=back
5741
5742=head2 Object property methods
5743
5744=over
5745
5746=item sign()
5747
5748    $x->sign();
5749
5750Return the sign, of $x, meaning either C<+>, C<->, C<-inf>, C<+inf> or NaN.
5751
5752If you want $x to have a certain sign, use one of the following methods:
5753
5754    $x->babs();                 # '+'
5755    $x->babs()->bneg();         # '-'
5756    $x->bnan();                 # 'NaN'
5757    $x->binf();                 # '+inf'
5758    $x->binf('-');              # '-inf'
5759
5760=item digit()
5761
5762    $x->digit($n);       # return the nth digit, counting from right
5763
5764If C<$n> is negative, returns the digit counting from left.
5765
5766=item digitsum()
5767
5768    $x->digitsum();
5769
5770Computes the sum of the base 10 digits and returns it.
5771
5772=item bdigitsum()
5773
5774    $x->bdigitsum();
5775
5776Computes the sum of the base 10 digits and assigns the result to the invocand.
5777
5778=item length()
5779
5780    $x->length();
5781    ($xl, $fl) = $x->length();
5782
5783Returns the number of digits in the decimal representation of the number. In
5784list context, returns the length of the integer and fraction part. For
5785Math::BigInt objects, the length of the fraction part is always 0.
5786
5787The following probably doesn't do what you expect:
5788
5789    $c = Math::BigInt->new(123);
5790    print $c->length(),"\n";                # prints 30
5791
5792It prints both the number of digits in the number and in the fraction part
5793since print calls C<length()> in list context. Use something like:
5794
5795    print scalar $c->length(),"\n";         # prints 3
5796
5797=item mantissa()
5798
5799    $x->mantissa();
5800
5801Return the signed mantissa of $x as a Math::BigInt.
5802
5803=item exponent()
5804
5805    $x->exponent();
5806
5807Return the exponent of $x as a Math::BigInt.
5808
5809=item parts()
5810
5811    $x->parts();
5812
5813Returns the significand (mantissa) and the exponent as integers. In
5814Math::BigFloat, both are returned as Math::BigInt objects.
5815
5816=item sparts()
5817
5818Returns the significand (mantissa) and the exponent as integers. In scalar
5819context, only the significand is returned. The significand is the integer with
5820the smallest absolute value. The output of C<sparts()> corresponds to the
5821output from C<bsstr()>.
5822
5823In Math::BigInt, this method is identical to C<parts()>.
5824
5825=item nparts()
5826
5827Returns the significand (mantissa) and exponent corresponding to normalized
5828notation. In scalar context, only the significand is returned. For finite
5829non-zero numbers, the significand's absolute value is greater than or equal to
58301 and less than 10. The output of C<nparts()> corresponds to the output from
5831C<bnstr()>. In Math::BigInt, if the significand can not be represented as an
5832integer, upgrading is performed or NaN is returned.
5833
5834=item eparts()
5835
5836Returns the significand (mantissa) and exponent corresponding to engineering
5837notation. In scalar context, only the significand is returned. For finite
5838non-zero numbers, the significand's absolute value is greater than or equal to
58391 and less than 1000, and the exponent is a multiple of 3. The output of
5840C<eparts()> corresponds to the output from C<bestr()>. In Math::BigInt, if the
5841significand can not be represented as an integer, upgrading is performed or NaN
5842is returned.
5843
5844=item dparts()
5845
5846Returns the integer part and the fraction part. If the fraction part can not be
5847represented as an integer, upgrading is performed or NaN is returned. The
5848output of C<dparts()> corresponds to the output from C<bdstr()>.
5849
5850=back
5851
5852=head2 String conversion methods
5853
5854=over
5855
5856=item bstr()
5857
5858Returns a string representing the number using decimal notation. In
5859Math::BigFloat, the output is zero padded according to the current accuracy or
5860precision, if any of those are defined.
5861
5862=item bsstr()
5863
5864Returns a string representing the number using scientific notation where both
5865the significand (mantissa) and the exponent are integers. The output
5866corresponds to the output from C<sparts()>.
5867
5868      123 is returned as "123e+0"
5869     1230 is returned as "123e+1"
5870    12300 is returned as "123e+2"
5871    12000 is returned as "12e+3"
5872    10000 is returned as "1e+4"
5873
5874=item bnstr()
5875
5876Returns a string representing the number using normalized notation, the most
5877common variant of scientific notation. For finite non-zero numbers, the
5878absolute value of the significand is greater than or equal to 1 and less than
587910. The output corresponds to the output from C<nparts()>.
5880
5881      123 is returned as "1.23e+2"
5882     1230 is returned as "1.23e+3"
5883    12300 is returned as "1.23e+4"
5884    12000 is returned as "1.2e+4"
5885    10000 is returned as "1e+4"
5886
5887=item bestr()
5888
5889Returns a string representing the number using engineering notation. For finite
5890non-zero numbers, the absolute value of the significand is greater than or
5891equal to 1 and less than 1000, and the exponent is a multiple of 3. The output
5892corresponds to the output from C<eparts()>.
5893
5894      123 is returned as "123e+0"
5895     1230 is returned as "1.23e+3"
5896    12300 is returned as "12.3e+3"
5897    12000 is returned as "12e+3"
5898    10000 is returned as "10e+3"
5899
5900=item bdstr()
5901
5902Returns a string representing the number using decimal notation. The output
5903corresponds to the output from C<dparts()>.
5904
5905      123 is returned as "123"
5906     1230 is returned as "1230"
5907    12300 is returned as "12300"
5908    12000 is returned as "12000"
5909    10000 is returned as "10000"
5910
5911=item to_hex()
5912
5913    $x->to_hex();
5914
5915Returns a hexadecimal string representation of the number. See also from_hex().
5916
5917=item to_bin()
5918
5919    $x->to_bin();
5920
5921Returns a binary string representation of the number. See also from_bin().
5922
5923=item to_oct()
5924
5925    $x->to_oct();
5926
5927Returns an octal string representation of the number. See also from_oct().
5928
5929=item to_bytes()
5930
5931    $x = Math::BigInt->new("1667327589");
5932    $s = $x->to_bytes();                    # $s = "cafe"
5933
5934Returns a byte string representation of the number using big endian byte
5935order. The invocand must be a non-negative, finite integer. See also from_bytes().
5936
5937=item to_base()
5938
5939    $x = Math::BigInt->new("250");
5940    $x->to_base(2);     # returns "11111010"
5941    $x->to_base(8);     # returns "372"
5942    $x->to_base(16);    # returns "fa"
5943
5944Returns a string representation of the number in the given base. If a collation
5945sequence is given, the collation sequence determines which characters are used
5946in the output.
5947
5948Here are some more examples
5949
5950    $x = Math::BigInt->new("16")->to_base(3);       # returns "121"
5951    $x = Math::BigInt->new("44027")->to_base(36);   # returns "XYZ"
5952    $x = Math::BigInt->new("58314")->to_base(42);   # returns "Why"
5953    $x = Math::BigInt->new("4")->to_base(2, "-|");  # returns "|--"
5954
5955See from_base() for information and examples.
5956
5957=item as_hex()
5958
5959    $x->as_hex();
5960
5961As, C<to_hex()>, but with a "0x" prefix.
5962
5963=item as_bin()
5964
5965    $x->as_bin();
5966
5967As, C<to_bin()>, but with a "0b" prefix.
5968
5969=item as_oct()
5970
5971    $x->as_oct();
5972
5973As, C<to_oct()>, but with a "0" prefix.
5974
5975=item as_bytes()
5976
5977This is just an alias for C<to_bytes()>.
5978
5979=back
5980
5981=head2 Other conversion methods
5982
5983=over
5984
5985=item numify()
5986
5987    print $x->numify();
5988
5989Returns a Perl scalar from $x. It is used automatically whenever a scalar is
5990needed, for instance in array index operations.
5991
5992=back
5993
5994=head1 ACCURACY and PRECISION
5995
5996Math::BigInt and Math::BigFloat have full support for accuracy and precision
5997based rounding, both automatically after every operation, as well as manually.
5998
5999This section describes the accuracy/precision handling in Math::BigInt and
6000Math::BigFloat as it used to be and as it is now, complete with an explanation
6001of all terms and abbreviations.
6002
6003Not yet implemented things (but with correct description) are marked with '!',
6004things that need to be answered are marked with '?'.
6005
6006In the next paragraph follows a short description of terms used here (because
6007these may differ from terms used by others people or documentation).
6008
6009During the rest of this document, the shortcuts A (for accuracy), P (for
6010precision), F (fallback) and R (rounding mode) are be used.
6011
6012=head2 Precision P
6013
6014Precision is a fixed number of digits before (positive) or after (negative) the
6015decimal point. For example, 123.45 has a precision of -2. 0 means an integer
6016like 123 (or 120). A precision of 2 means at least two digits to the left of
6017the decimal point are zero, so 123 with P = 1 becomes 120. Note that numbers
6018with zeros before the decimal point may have different precisions, because 1200
6019can have P = 0, 1 or 2 (depending on what the initial value was). It could also
6020have p < 0, when the digits after the decimal point are zero.
6021
6022The string output (of floating point numbers) is padded with zeros:
6023
6024    Initial value    P      A       Result          String
6025    ------------------------------------------------------------
6026    1234.01         -3              1000            1000
6027    1234            -2              1200            1200
6028    1234.5          -1              1230            1230
6029    1234.001         1              1234            1234.0
6030    1234.01          0              1234            1234
6031    1234.01          2              1234.01         1234.01
6032    1234.01          5              1234.01         1234.01000
6033
6034For Math::BigInt objects, no padding occurs.
6035
6036=head2 Accuracy A
6037
6038Number of significant digits. Leading zeros are not counted. A number may have
6039an accuracy greater than the non-zero digits when there are zeros in it or
6040trailing zeros. For example, 123.456 has A of 6, 10203 has 5, 123.0506 has 7,
6041123.45000 has 8 and 0.000123 has 3.
6042
6043The string output (of floating point numbers) is padded with zeros:
6044
6045    Initial value    P      A       Result          String
6046    ------------------------------------------------------------
6047    1234.01                 3       1230            1230
6048    1234.01                 6       1234.01         1234.01
6049    1234.1                  8       1234.1          1234.1000
6050
6051For Math::BigInt objects, no padding occurs.
6052
6053=head2 Fallback F
6054
6055When both A and P are undefined, this is used as a fallback accuracy when
6056dividing numbers.
6057
6058=head2 Rounding mode R
6059
6060When rounding a number, different 'styles' or 'kinds' of rounding are possible.
6061(Note that random rounding, as in Math::Round, is not implemented.)
6062
6063=head3 Directed rounding
6064
6065These round modes always round in the same direction.
6066
6067=over
6068
6069=item 'trunc'
6070
6071Round towards zero. Remove all digits following the rounding place, i.e.,
6072replace them with zeros. Thus, 987.65 rounded to tens (P=1) becomes 980, and
6073rounded to the fourth significant digit becomes 987.6 (A=4). 123.456 rounded to
6074the second place after the decimal point (P=-2) becomes 123.46. This
6075corresponds to the IEEE 754 rounding mode 'roundTowardZero'.
6076
6077=back
6078
6079=head3 Rounding to nearest
6080
6081These rounding modes round to the nearest digit. They differ in how they
6082determine which way to round in the ambiguous case when there is a tie.
6083
6084=over
6085
6086=item 'even'
6087
6088Round towards the nearest even digit, e.g., when rounding to nearest integer,
6089-5.5 becomes -6, 4.5 becomes 4, but 4.501 becomes 5. This corresponds to the
6090IEEE 754 rounding mode 'roundTiesToEven'.
6091
6092=item 'odd'
6093
6094Round towards the nearest odd digit, e.g., when rounding to nearest integer,
60954.5 becomes 5, -5.5 becomes -5, but 5.501 becomes 6. This corresponds to the
6096IEEE 754 rounding mode 'roundTiesToOdd'.
6097
6098=item '+inf'
6099
6100Round towards plus infinity, i.e., always round up. E.g., when rounding to the
6101nearest integer, 4.5 becomes 5, -5.5 becomes -5, and 4.501 also becomes 5. This
6102corresponds to the IEEE 754 rounding mode 'roundTiesToPositive'.
6103
6104=item '-inf'
6105
6106Round towards minus infinity, i.e., always round down. E.g., when rounding to
6107the nearest integer, 4.5 becomes 4, -5.5 becomes -6, but 4.501 becomes 5. This
6108corresponds to the IEEE 754 rounding mode 'roundTiesToNegative'.
6109
6110=item 'zero'
6111
6112Round towards zero, i.e., round positive numbers down and negative numbers up.
6113E.g., when rounding to the nearest integer, 4.5 becomes 4, -5.5 becomes -5, but
61144.501 becomes 5. This corresponds to the IEEE 754 rounding mode
6115'roundTiesToZero'.
6116
6117=item 'common'
6118
6119Round away from zero, i.e., round to the number with the largest absolute
6120value. E.g., when rounding to the nearest integer, -1.5 becomes -2, 1.5 becomes
61212 and 1.49 becomes 1. This corresponds to the IEEE 754 rounding mode
6122'roundTiesToAway'.
6123
6124=back
6125
6126The handling of A & P in MBI/MBF (the old core code shipped with Perl versions
6127<= 5.7.2) is like this:
6128
6129=over
6130
6131=item Precision
6132
6133  * bfround($p) is able to round to $p number of digits after the decimal
6134    point
6135  * otherwise P is unused
6136
6137=item Accuracy (significant digits)
6138
6139  * bround($a) rounds to $a significant digits
6140  * only bdiv() and bsqrt() take A as (optional) parameter
6141    + other operations simply create the same number (bneg etc), or
6142      more (bmul) of digits
6143    + rounding/truncating is only done when explicitly calling one
6144      of bround or bfround, and never for Math::BigInt (not implemented)
6145  * bsqrt() simply hands its accuracy argument over to bdiv.
6146  * the documentation and the comment in the code indicate two
6147    different ways on how bdiv() determines the maximum number
6148    of digits it should calculate, and the actual code does yet
6149    another thing
6150    POD:
6151      max($Math::BigFloat::div_scale,length(dividend)+length(divisor))
6152    Comment:
6153      result has at most max(scale, length(dividend), length(divisor)) digits
6154    Actual code:
6155      scale = max(scale, length(dividend)-1,length(divisor)-1);
6156      scale += length(divisor) - length(dividend);
6157    So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10
6158    So for lx = 3, ly = 9, scale = 10, scale will actually be 16
6159    (10+9-3). Actually, the 'difference' added to the scale is cal-
6160    culated from the number of "significant digits" in dividend and
6161    divisor, which is derived by looking at the length of the man-
6162    tissa. Which is wrong, since it includes the + sign (oops) and
6163    actually gets 2 for '+100' and 4 for '+101'. Oops again. Thus
6164    124/3 with div_scale=1 will get you '41.3' based on the strange
6165    assumption that 124 has 3 significant digits, while 120/7 will
6166    get you '17', not '17.1' since 120 is thought to have 2 signif-
6167    icant digits. The rounding after the division then uses the
6168    remainder and $y to determine whether it must round up or down.
6169 ?  I have no idea which is the right way. That's why I used a slightly more
6170 ?  simple scheme and tweaked the few failing testcases to match it.
6171
6172=back
6173
6174This is how it works now:
6175
6176=over
6177
6178=item Setting/Accessing
6179
6180  * You can set the A global via Math::BigInt->accuracy() or
6181    Math::BigFloat->accuracy() or whatever class you are using.
6182  * You can also set P globally by using Math::SomeClass->precision()
6183    likewise.
6184  * Globals are classwide, and not inherited by subclasses.
6185  * to undefine A, use Math::SomeCLass->accuracy(undef);
6186  * to undefine P, use Math::SomeClass->precision(undef);
6187  * Setting Math::SomeClass->accuracy() clears automatically
6188    Math::SomeClass->precision(), and vice versa.
6189  * To be valid, A must be > 0, P can have any value.
6190  * If P is negative, this means round to the P'th place to the right of the
6191    decimal point; positive values mean to the left of the decimal point.
6192    P of 0 means round to integer.
6193  * to find out the current global A, use Math::SomeClass->accuracy()
6194  * to find out the current global P, use Math::SomeClass->precision()
6195  * use $x->accuracy() respective $x->precision() for the local
6196    setting of $x.
6197  * Please note that $x->accuracy() respective $x->precision()
6198    return eventually defined global A or P, when $x's A or P is not
6199    set.
6200
6201=item Creating numbers
6202
6203  * When you create a number, you can give the desired A or P via:
6204    $x = Math::BigInt->new($number,$A,$P);
6205  * Only one of A or P can be defined, otherwise the result is NaN
6206  * If no A or P is give ($x = Math::BigInt->new($number) form), then the
6207    globals (if set) will be used. Thus changing the global defaults later on
6208    will not change the A or P of previously created numbers (i.e., A and P of
6209    $x will be what was in effect when $x was created)
6210  * If given undef for A and P, NO rounding will occur, and the globals will
6211    NOT be used. This is used by subclasses to create numbers without
6212    suffering rounding in the parent. Thus a subclass is able to have its own
6213    globals enforced upon creation of a number by using
6214    $x = Math::BigInt->new($number,undef,undef):
6215
6216        use Math::BigInt::SomeSubclass;
6217        use Math::BigInt;
6218
6219        Math::BigInt->accuracy(2);
6220        Math::BigInt::SomeSubClass->accuracy(3);
6221        $x = Math::BigInt::SomeSubClass->new(1234);
6222
6223    $x is now 1230, and not 1200. A subclass might choose to implement
6224    this otherwise, e.g. falling back to the parent's A and P.
6225
6226=item Usage
6227
6228  * If A or P are enabled/defined, they are used to round the result of each
6229    operation according to the rules below
6230  * Negative P is ignored in Math::BigInt, since Math::BigInt objects never
6231    have digits after the decimal point
6232  * Math::BigFloat uses Math::BigInt internally, but setting A or P inside
6233    Math::BigInt as globals does not tamper with the parts of a Math::BigFloat.
6234    A flag is used to mark all Math::BigFloat numbers as 'never round'.
6235
6236=item Precedence
6237
6238  * It only makes sense that a number has only one of A or P at a time.
6239    If you set either A or P on one object, or globally, the other one will
6240    be automatically cleared.
6241  * If two objects are involved in an operation, and one of them has A in
6242    effect, and the other P, this results in an error (NaN).
6243  * A takes precedence over P (Hint: A comes before P).
6244    If neither of them is defined, nothing is used, i.e. the result will have
6245    as many digits as it can (with an exception for bdiv/bsqrt) and will not
6246    be rounded.
6247  * There is another setting for bdiv() (and thus for bsqrt()). If neither of
6248    A or P is defined, bdiv() will use a fallback (F) of $div_scale digits.
6249    If either the dividend's or the divisor's mantissa has more digits than
6250    the value of F, the higher value will be used instead of F.
6251    This is to limit the digits (A) of the result (just consider what would
6252    happen with unlimited A and P in the case of 1/3 :-)
6253  * bdiv will calculate (at least) 4 more digits than required (determined by
6254    A, P or F), and, if F is not used, round the result
6255    (this will still fail in the case of a result like 0.12345000000001 with A
6256    or P of 5, but this can not be helped - or can it?)
6257  * Thus you can have the math done by on Math::Big* class in two modi:
6258    + never round (this is the default):
6259      This is done by setting A and P to undef. No math operation
6260      will round the result, with bdiv() and bsqrt() as exceptions to guard
6261      against overflows. You must explicitly call bround(), bfround() or
6262      round() (the latter with parameters).
6263      Note: Once you have rounded a number, the settings will 'stick' on it
6264      and 'infect' all other numbers engaged in math operations with it, since
6265      local settings have the highest precedence. So, to get SaferRound[tm],
6266      use a copy() before rounding like this:
6267
6268        $x = Math::BigFloat->new(12.34);
6269        $y = Math::BigFloat->new(98.76);
6270        $z = $x * $y;                           # 1218.6984
6271        print $x->copy()->bround(3);            # 12.3 (but A is now 3!)
6272        $z = $x * $y;                           # still 1218.6984, without
6273                                                # copy would have been 1210!
6274
6275    + round after each op:
6276      After each single operation (except for testing like is_zero()), the
6277      method round() is called and the result is rounded appropriately. By
6278      setting proper values for A and P, you can have all-the-same-A or
6279      all-the-same-P modes. For example, Math::Currency might set A to undef,
6280      and P to -2, globally.
6281
6282 ?Maybe an extra option that forbids local A & P settings would be in order,
6283 ?so that intermediate rounding does not 'poison' further math?
6284
6285=item Overriding globals
6286
6287  * you will be able to give A, P and R as an argument to all the calculation
6288    routines; the second parameter is A, the third one is P, and the fourth is
6289    R (shift right by one for binary operations like badd). P is used only if
6290    the first parameter (A) is undefined. These three parameters override the
6291    globals in the order detailed as follows, i.e. the first defined value
6292    wins:
6293    (local: per object, global: global default, parameter: argument to sub)
6294      + parameter A
6295      + parameter P
6296      + local A (if defined on both of the operands: smaller one is taken)
6297      + local P (if defined on both of the operands: bigger one is taken)
6298      + global A
6299      + global P
6300      + global F
6301  * bsqrt() will hand its arguments to bdiv(), as it used to, only now for two
6302    arguments (A and P) instead of one
6303
6304=item Local settings
6305
6306  * You can set A or P locally by using $x->accuracy() or
6307    $x->precision()
6308    and thus force different A and P for different objects/numbers.
6309  * Setting A or P this way immediately rounds $x to the new value.
6310  * $x->accuracy() clears $x->precision(), and vice versa.
6311
6312=item Rounding
6313
6314  * the rounding routines will use the respective global or local settings.
6315    bround() is for accuracy rounding, while bfround() is for precision
6316  * the two rounding functions take as the second parameter one of the
6317    following rounding modes (R):
6318    'even', 'odd', '+inf', '-inf', 'zero', 'trunc', 'common'
6319  * you can set/get the global R by using Math::SomeClass->round_mode()
6320    or by setting $Math::SomeClass::round_mode
6321  * after each operation, $result->round() is called, and the result may
6322    eventually be rounded (that is, if A or P were set either locally,
6323    globally or as parameter to the operation)
6324  * to manually round a number, call $x->round($A,$P,$round_mode);
6325    this will round the number by using the appropriate rounding function
6326    and then normalize it.
6327  * rounding modifies the local settings of the number:
6328
6329        $x = Math::BigFloat->new(123.456);
6330        $x->accuracy(5);
6331        $x->bround(4);
6332
6333    Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy()
6334    will be 4 from now on.
6335
6336=item Default values
6337
6338  * R: 'even'
6339  * F: 40
6340  * A: undef
6341  * P: undef
6342
6343=item Remarks
6344
6345  * The defaults are set up so that the new code gives the same results as
6346    the old code (except in a few cases on bdiv):
6347    + Both A and P are undefined and thus will not be used for rounding
6348      after each operation.
6349    + round() is thus a no-op, unless given extra parameters A and P
6350
6351=back
6352
6353=head1 Infinity and Not a Number
6354
6355While Math::BigInt has extensive handling of inf and NaN, certain quirks
6356remain.
6357
6358=over
6359
6360=item oct()/hex()
6361
6362These perl routines currently (as of Perl v.5.8.6) cannot handle passed inf.
6363
6364    te@linux:~> perl -wle 'print 2 ** 3333'
6365    Inf
6366    te@linux:~> perl -wle 'print 2 ** 3333 == 2 ** 3333'
6367    1
6368    te@linux:~> perl -wle 'print oct(2 ** 3333)'
6369    0
6370    te@linux:~> perl -wle 'print hex(2 ** 3333)'
6371    Illegal hexadecimal digit 'I' ignored at -e line 1.
6372    0
6373
6374The same problems occur if you pass them Math::BigInt->binf() objects. Since
6375overloading these routines is not possible, this cannot be fixed from
6376Math::BigInt.
6377
6378=back
6379
6380=head1 INTERNALS
6381
6382You should neither care about nor depend on the internal representation; it
6383might change without notice. Use B<ONLY> method calls like C<< $x->sign(); >>
6384instead relying on the internal representation.
6385
6386=head2 MATH LIBRARY
6387
6388Math with the numbers is done (by default) by a module called
6389C<Math::BigInt::Calc>. This is equivalent to saying:
6390
6391    use Math::BigInt try => 'Calc';
6392
6393You can change this backend library by using:
6394
6395    use Math::BigInt try => 'GMP';
6396
6397B<Note>: General purpose packages should not be explicit about the library to
6398use; let the script author decide which is best.
6399
6400If your script works with huge numbers and Calc is too slow for them, you can
6401also for the loading of one of these libraries and if none of them can be used,
6402the code dies:
6403
6404    use Math::BigInt only => 'GMP,Pari';
6405
6406The following would first try to find Math::BigInt::Foo, then
6407Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
6408
6409    use Math::BigInt try => 'Foo,Math::BigInt::Bar';
6410
6411The library that is loaded last is used. Note that this can be overwritten at
6412any time by loading a different library, and numbers constructed with different
6413libraries cannot be used in math operations together.
6414
6415=head3 What library to use?
6416
6417B<Note>: General purpose packages should not be explicit about the library to
6418use; let the script author decide which is best.
6419
6420L<Math::BigInt::GMP> and L<Math::BigInt::Pari> are in cases involving big
6421numbers much faster than Calc, however it is slower when dealing with very
6422small numbers (less than about 20 digits) and when converting very large
6423numbers to decimal (for instance for printing, rounding, calculating their
6424length in decimal etc).
6425
6426So please select carefully what library you want to use.
6427
6428Different low-level libraries use different formats to store the numbers.
6429However, you should B<NOT> depend on the number having a specific format
6430internally.
6431
6432See the respective math library module documentation for further details.
6433
6434=head2 SIGN
6435
6436The sign is either '+', '-', 'NaN', '+inf' or '-inf'.
6437
6438A sign of 'NaN' is used to represent the result when input arguments are not
6439numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively
6440minus infinity. You get '+inf' when dividing a positive number by 0, and '-inf'
6441when dividing any negative number by 0.
6442
6443=head1 EXAMPLES
6444
6445  use Math::BigInt;
6446
6447  sub bigint { Math::BigInt->new(shift); }
6448
6449  $x = Math::BigInt->bstr("1234")       # string "1234"
6450  $x = "$x";                            # same as bstr()
6451  $x = Math::BigInt->bneg("1234");      # Math::BigInt "-1234"
6452  $x = Math::BigInt->babs("-12345");    # Math::BigInt "12345"
6453  $x = Math::BigInt->bnorm("-0.00");    # Math::BigInt "0"
6454  $x = bigint(1) + bigint(2);           # Math::BigInt "3"
6455  $x = bigint(1) + "2";                 # ditto (auto-Math::BigIntify of "2")
6456  $x = bigint(1);                       # Math::BigInt "1"
6457  $x = $x + 5 / 2;                      # Math::BigInt "3"
6458  $x = $x ** 3;                         # Math::BigInt "27"
6459  $x *= 2;                              # Math::BigInt "54"
6460  $x = Math::BigInt->new(0);            # Math::BigInt "0"
6461  $x--;                                 # Math::BigInt "-1"
6462  $x = Math::BigInt->badd(4,5)          # Math::BigInt "9"
6463  print $x->bsstr();                    # 9e+0
6464
6465Examples for rounding:
6466
6467  use Math::BigFloat;
6468  use Test::More;
6469
6470  $x = Math::BigFloat->new(123.4567);
6471  $y = Math::BigFloat->new(123.456789);
6472  Math::BigFloat->accuracy(4);          # no more A than 4
6473
6474  is ($x->copy()->bround(),123.4);      # even rounding
6475  print $x->copy()->bround(),"\n";      # 123.4
6476  Math::BigFloat->round_mode('odd');    # round to odd
6477  print $x->copy()->bround(),"\n";      # 123.5
6478  Math::BigFloat->accuracy(5);          # no more A than 5
6479  Math::BigFloat->round_mode('odd');    # round to odd
6480  print $x->copy()->bround(),"\n";      # 123.46
6481  $y = $x->copy()->bround(4),"\n";      # A = 4: 123.4
6482  print "$y, ",$y->accuracy(),"\n";     # 123.4, 4
6483
6484  Math::BigFloat->accuracy(undef);      # A not important now
6485  Math::BigFloat->precision(2);         # P important
6486  print $x->copy()->bnorm(),"\n";       # 123.46
6487  print $x->copy()->bround(),"\n";      # 123.46
6488
6489Examples for converting:
6490
6491  my $x = Math::BigInt->new('0b1'.'01' x 123);
6492  print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n";
6493
6494=head1 Autocreating constants
6495
6496After C<use Math::BigInt ':constant'> all the B<integer> decimal, hexadecimal
6497and binary constants in the given scope are converted to C<Math::BigInt>. This
6498conversion happens at compile time.
6499
6500In particular,
6501
6502  perl -MMath::BigInt=:constant -e 'print 2**100,"\n"'
6503
6504prints the integer value of C<2**100>. Note that without conversion of
6505constants the expression 2**100 is calculated using Perl scalars.
6506
6507Please note that strings and floating point constants are not affected, so that
6508
6509    use Math::BigInt qw/:constant/;
6510
6511    $x = 1234567890123456789012345678901234567890
6512            + 123456789123456789;
6513    $y = '1234567890123456789012345678901234567890'
6514            + '123456789123456789';
6515
6516does not give you what you expect. You need an explicit Math::BigInt->new()
6517around one of the operands. You should also quote large constants to protect
6518loss of precision:
6519
6520    use Math::BigInt;
6521
6522    $x = Math::BigInt->new('1234567889123456789123456789123456789');
6523
6524Without the quotes Perl would convert the large number to a floating point
6525constant at compile time and then hand the result to Math::BigInt, which
6526results in an truncated result or a NaN.
6527
6528This also applies to integers that look like floating point constants:
6529
6530    use Math::BigInt ':constant';
6531
6532    print ref(123e2),"\n";
6533    print ref(123.2e2),"\n";
6534
6535prints nothing but newlines. Use either L<bignum> or L<Math::BigFloat> to get
6536this to work.
6537
6538=head1 PERFORMANCE
6539
6540Using the form $x += $y; etc over $x = $x + $y is faster, since a copy of $x
6541must be made in the second case. For long numbers, the copy can eat up to 20%
6542of the work (in the case of addition/subtraction, less for
6543multiplication/division). If $y is very small compared to $x, the form $x += $y
6544is MUCH faster than $x = $x + $y since making the copy of $x takes more time
6545then the actual addition.
6546
6547With a technique called copy-on-write, the cost of copying with overload could
6548be minimized or even completely avoided. A test implementation of COW did show
6549performance gains for overloaded math, but introduced a performance loss due to
6550a constant overhead for all other operations. So Math::BigInt does currently
6551not COW.
6552
6553The rewritten version of this module (vs. v0.01) is slower on certain
6554operations, like C<new()>, C<bstr()> and C<numify()>. The reason are that it
6555does now more work and handles much more cases. The time spent in these
6556operations is usually gained in the other math operations so that code on the
6557average should get (much) faster. If they don't, please contact the author.
6558
6559Some operations may be slower for small numbers, but are significantly faster
6560for big numbers. Other operations are now constant (O(1), like C<bneg()>,
6561C<babs()> etc), instead of O(N) and thus nearly always take much less time.
6562These optimizations were done on purpose.
6563
6564If you find the Calc module to slow, try to install any of the replacement
6565modules and see if they help you.
6566
6567=head2 Alternative math libraries
6568
6569You can use an alternative library to drive Math::BigInt. See the section
6570L</MATH LIBRARY> for more information.
6571
6572For more benchmark results see L<http://bloodgate.com/perl/benchmarks.html>.
6573
6574=head1 SUBCLASSING
6575
6576=head2 Subclassing Math::BigInt
6577
6578The basic design of Math::BigInt allows simple subclasses with very little
6579work, as long as a few simple rules are followed:
6580
6581=over
6582
6583=item *
6584
6585The public API must remain consistent, i.e. if a sub-class is overloading
6586addition, the sub-class must use the same name, in this case badd(). The reason
6587for this is that Math::BigInt is optimized to call the object methods directly.
6588
6589=item *
6590
6591The private object hash keys like C<< $x->{sign} >> may not be changed, but
6592additional keys can be added, like C<< $x->{_custom} >>.
6593
6594=item *
6595
6596Accessor functions are available for all existing object hash keys and should
6597be used instead of directly accessing the internal hash keys. The reason for
6598this is that Math::BigInt itself has a pluggable interface which permits it to
6599support different storage methods.
6600
6601=back
6602
6603More complex sub-classes may have to replicate more of the logic internal of
6604Math::BigInt if they need to change more basic behaviors. A subclass that needs
6605to merely change the output only needs to overload C<bstr()>.
6606
6607All other object methods and overloaded functions can be directly inherited
6608from the parent class.
6609
6610At the very minimum, any subclass needs to provide its own C<new()> and can
6611store additional hash keys in the object. There are also some package globals
6612that must be defined, e.g.:
6613
6614    # Globals
6615    $accuracy = undef;
6616    $precision = -2;       # round to 2 decimal places
6617    $round_mode = 'even';
6618    $div_scale = 40;
6619
6620Additionally, you might want to provide the following two globals to allow
6621auto-upgrading and auto-downgrading to work correctly:
6622
6623    $upgrade = undef;
6624    $downgrade = undef;
6625
6626This allows Math::BigInt to correctly retrieve package globals from the
6627subclass, like C<$SubClass::precision>. See t/Math/BigInt/Subclass.pm or
6628t/Math/BigFloat/SubClass.pm completely functional subclass examples.
6629
6630Don't forget to
6631
6632    use overload;
6633
6634in your subclass to automatically inherit the overloading from the parent. If
6635you like, you can change part of the overloading, look at Math::String for an
6636example.
6637
6638=head1 UPGRADING
6639
6640When used like this:
6641
6642    use Math::BigInt upgrade => 'Foo::Bar';
6643
6644certain operations 'upgrade' their calculation and thus the result to the class
6645Foo::Bar. Usually this is used in conjunction with Math::BigFloat:
6646
6647    use Math::BigInt upgrade => 'Math::BigFloat';
6648
6649As a shortcut, you can use the module L<bignum>:
6650
6651    use bignum;
6652
6653Also good for one-liners:
6654
6655    perl -Mbignum -le 'print 2 ** 255'
6656
6657This makes it possible to mix arguments of different classes (as in 2.5 + 2) as
6658well es preserve accuracy (as in sqrt(3)).
6659
6660Beware: This feature is not fully implemented yet.
6661
6662=head2 Auto-upgrade
6663
6664The following methods upgrade themselves unconditionally; that is if upgrade is
6665in effect, they always hands up their work:
6666
6667    div bsqrt blog bexp bpi bsin bcos batan batan2
6668
6669All other methods upgrade themselves only when one (or all) of their arguments
6670are of the class mentioned in $upgrade.
6671
6672=head1 EXPORTS
6673
6674C<Math::BigInt> exports nothing by default, but can export the following
6675methods:
6676
6677    bgcd
6678    blcm
6679
6680=head1 CAVEATS
6681
6682Some things might not work as you expect them. Below is documented what is
6683known to be troublesome:
6684
6685=over
6686
6687=item Comparing numbers as strings
6688
6689Both C<bstr()> and C<bsstr()> as well as stringify via overload drop the
6690leading '+'. This is to be consistent with Perl and to make C<cmp> (especially
6691with overloading) to work as you expect. It also solves problems with
6692C<Test.pm> and L<Test::More>, which stringify arguments before comparing them.
6693
6694Mark Biggar said, when asked about to drop the '+' altogether, or make only
6695C<cmp> work:
6696
6697    I agree (with the first alternative), don't add the '+' on positive
6698    numbers.  It's not as important anymore with the new internal form
6699    for numbers.  It made doing things like abs and neg easier, but
6700    those have to be done differently now anyway.
6701
6702So, the following examples now works as expected:
6703
6704    use Test::More tests => 1;
6705    use Math::BigInt;
6706
6707    my $x = Math::BigInt -> new(3*3);
6708    my $y = Math::BigInt -> new(3*3);
6709
6710    is($x,3*3, 'multiplication');
6711    print "$x eq 9" if $x eq $y;
6712    print "$x eq 9" if $x eq '9';
6713    print "$x eq 9" if $x eq 3*3;
6714
6715Additionally, the following still works:
6716
6717    print "$x == 9" if $x == $y;
6718    print "$x == 9" if $x == 9;
6719    print "$x == 9" if $x == 3*3;
6720
6721There is now a C<bsstr()> method to get the string in scientific notation aka
6722C<1e+2> instead of C<100>. Be advised that overloaded 'eq' always uses bstr()
6723for comparison, but Perl represents some numbers as 100 and others as 1e+308.
6724If in doubt, convert both arguments to Math::BigInt before comparing them as
6725strings:
6726
6727    use Test::More tests => 3;
6728    use Math::BigInt;
6729
6730    $x = Math::BigInt->new('1e56'); $y = 1e56;
6731    is($x,$y);                     # fails
6732    is($x->bsstr(),$y);            # okay
6733    $y = Math::BigInt->new($y);
6734    is($x,$y);                     # okay
6735
6736Alternatively, simply use C<< <=> >> for comparisons, this always gets it
6737right. There is not yet a way to get a number automatically represented as a
6738string that matches exactly the way Perl represents it.
6739
6740See also the section about L<Infinity and Not a Number> for problems in
6741comparing NaNs.
6742
6743=item int()
6744
6745C<int()> returns (at least for Perl v5.7.1 and up) another Math::BigInt, not a
6746Perl scalar:
6747
6748    $x = Math::BigInt->new(123);
6749    $y = int($x);                           # 123 as a Math::BigInt
6750    $x = Math::BigFloat->new(123.45);
6751    $y = int($x);                           # 123 as a Math::BigFloat
6752
6753If you want a real Perl scalar, use C<numify()>:
6754
6755    $y = $x->numify();                      # 123 as a scalar
6756
6757This is seldom necessary, though, because this is done automatically, like when
6758you access an array:
6759
6760    $z = $array[$x];                        # does work automatically
6761
6762=item Modifying and =
6763
6764Beware of:
6765
6766    $x = Math::BigFloat->new(5);
6767    $y = $x;
6768
6769This makes a second reference to the B<same> object and stores it in $y. Thus
6770anything that modifies $x (except overloaded operators) also modifies $y, and
6771vice versa. Or in other words, C<=> is only safe if you modify your
6772Math::BigInt objects only via overloaded math. As soon as you use a method call
6773it breaks:
6774
6775    $x->bmul(2);
6776    print "$x, $y\n";       # prints '10, 10'
6777
6778If you want a true copy of $x, use:
6779
6780    $y = $x->copy();
6781
6782You can also chain the calls like this, this first makes a copy and then
6783multiply it by 2:
6784
6785    $y = $x->copy()->bmul(2);
6786
6787See also the documentation for overload.pm regarding C<=>.
6788
6789=item Overloading -$x
6790
6791The following:
6792
6793    $x = -$x;
6794
6795is slower than
6796
6797    $x->bneg();
6798
6799since overload calls C<sub($x,0,1);> instead of C<neg($x)>. The first variant
6800needs to preserve $x since it does not know that it later gets overwritten.
6801This makes a copy of $x and takes O(N), but $x->bneg() is O(1).
6802
6803=item Mixing different object types
6804
6805With overloaded operators, it is the first (dominating) operand that determines
6806which method is called. Here are some examples showing what actually gets
6807called in various cases.
6808
6809    use Math::BigInt;
6810    use Math::BigFloat;
6811
6812    $mbf  = Math::BigFloat->new(5);
6813    $mbi2 = Math::BigInt->new(5);
6814    $mbi  = Math::BigInt->new(2);
6815                                    # what actually gets called:
6816    $float = $mbf + $mbi;           # $mbf->badd($mbi)
6817    $float = $mbf / $mbi;           # $mbf->bdiv($mbi)
6818    $integer = $mbi + $mbf;         # $mbi->badd($mbf)
6819    $integer = $mbi2 / $mbi;        # $mbi2->bdiv($mbi)
6820    $integer = $mbi2 / $mbf;        # $mbi2->bdiv($mbf)
6821
6822For instance, Math::BigInt->bdiv() always returns a Math::BigInt, regardless of
6823whether the second operant is a Math::BigFloat. To get a Math::BigFloat you
6824either need to call the operation manually, make sure each operand already is a
6825Math::BigFloat, or cast to that type via Math::BigFloat->new():
6826
6827    $float = Math::BigFloat->new($mbi2) / $mbi;     # = 2.5
6828
6829Beware of casting the entire expression, as this would cast the
6830result, at which point it is too late:
6831
6832    $float = Math::BigFloat->new($mbi2 / $mbi);     # = 2
6833
6834Beware also of the order of more complicated expressions like:
6835
6836    $integer = ($mbi2 + $mbi) / $mbf;               # int / float => int
6837    $integer = $mbi2 / Math::BigFloat->new($mbi);   # ditto
6838
6839If in doubt, break the expression into simpler terms, or cast all operands
6840to the desired resulting type.
6841
6842Scalar values are a bit different, since:
6843
6844    $float = 2 + $mbf;
6845    $float = $mbf + 2;
6846
6847both result in the proper type due to the way the overloaded math works.
6848
6849This section also applies to other overloaded math packages, like Math::String.
6850
6851One solution to you problem might be autoupgrading|upgrading. See the
6852pragmas L<bignum>, L<bigint> and L<bigrat> for an easy way to do this.
6853
6854=back
6855
6856=head1 BUGS
6857
6858Please report any bugs or feature requests to
6859C<bug-math-bigint at rt.cpan.org>, or through the web interface at
6860L<https://rt.cpan.org/Ticket/Create.html?Queue=Math-BigInt> (requires login).
6861We will be notified, and then you'll automatically be notified of progress on
6862your bug as I make changes.
6863
6864=head1 SUPPORT
6865
6866You can find documentation for this module with the perldoc command.
6867
6868    perldoc Math::BigInt
6869
6870You can also look for information at:
6871
6872=over 4
6873
6874=item * RT: CPAN's request tracker
6875
6876L<https://rt.cpan.org/Public/Dist/Display.html?Name=Math-BigInt>
6877
6878=item * AnnoCPAN: Annotated CPAN documentation
6879
6880L<http://annocpan.org/dist/Math-BigInt>
6881
6882=item * CPAN Ratings
6883
6884L<https://cpanratings.perl.org/dist/Math-BigInt>
6885
6886=item * MetaCPAN
6887
6888L<https://metacpan.org/release/Math-BigInt>
6889
6890=item * CPAN Testers Matrix
6891
6892L<http://matrix.cpantesters.org/?dist=Math-BigInt>
6893
6894=item * The Bignum mailing list
6895
6896=over 4
6897
6898=item * Post to mailing list
6899
6900C<bignum at lists.scsys.co.uk>
6901
6902=item * View mailing list
6903
6904L<http://lists.scsys.co.uk/pipermail/bignum/>
6905
6906=item * Subscribe/Unsubscribe
6907
6908L<http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/bignum>
6909
6910=back
6911
6912=back
6913
6914=head1 LICENSE
6915
6916This program is free software; you may redistribute it and/or modify it under
6917the same terms as Perl itself.
6918
6919=head1 SEE ALSO
6920
6921L<Math::BigFloat> and L<Math::BigRat> as well as the backends
6922L<Math::BigInt::FastCalc>, L<Math::BigInt::GMP>, and L<Math::BigInt::Pari>.
6923
6924The pragmas L<bignum>, L<bigint> and L<bigrat> also might be of interest
6925because they solve the autoupgrading/downgrading issue, at least partly.
6926
6927=head1 AUTHORS
6928
6929=over 4
6930
6931=item *
6932
6933Mark Biggar, overloaded interface by Ilya Zakharevich, 1996-2001.
6934
6935=item *
6936
6937Completely rewritten by Tels L<http://bloodgate.com>, 2001-2008.
6938
6939=item *
6940
6941Florian Ragwitz E<lt>flora@cpan.orgE<gt>, 2010.
6942
6943=item *
6944
6945Peter John Acklam E<lt>pjacklam@online.noE<gt>, 2011-.
6946
6947=back
6948
6949Many people contributed in one or more ways to the final beast, see the file
6950CREDITS for an (incomplete) list. If you miss your name, please drop me a
6951mail. Thank you!
6952
6953=cut
6954