Upgrade to Math::BigInt 1.57.
[p5sagit/p5-mst-13.2.git] / lib / Math / BigInt.pm
1 package Math::BigInt;
2
3 #
4 # "Mike had an infinite amount to do and a negative amount of time in which
5 # to do it." - Before and After
6 #
7
8 # The following hash values are used:
9 #   value: unsigned int with actual value (as a Math::BigInt::Calc or similiar)
10 #   sign : +,-,NaN,+inf,-inf
11 #   _a   : accuracy
12 #   _p   : precision
13 #   _f   : flags, used by MBF to flag parts of a float as untouchable
14
15 # Remember not to take shortcuts ala $xs = $x->{value}; $CALC->foo($xs); since
16 # underlying lib might change the reference!
17
18 my $class = "Math::BigInt";
19 require 5.005;
20
21 $VERSION = '1.57';
22 use Exporter;
23 @ISA =       qw( Exporter );
24 @EXPORT_OK = qw( objectify _swap bgcd blcm); 
25 use vars qw/$round_mode $accuracy $precision $div_scale $rnd_mode/;
26 use vars qw/$upgrade $downgrade/;
27 use strict;
28
29 # Inside overload, the first arg is always an object. If the original code had
30 # it reversed (like $x = 2 * $y), then the third paramater indicates this
31 # swapping. To make it work, we use a helper routine which not only reswaps the
32 # params, but also makes a new object in this case. See _swap() for details,
33 # especially the cases of operators with different classes.
34
35 # For overloaded ops with only one argument we simple use $_[0]->copy() to
36 # preserve the argument.
37
38 # Thus inheritance of overload operators becomes possible and transparent for
39 # our subclasses without the need to repeat the entire overload section there.
40
41 use overload
42 '='     =>      sub { $_[0]->copy(); },
43
44 # '+' and '-' do not use _swap, since it is a triffle slower. If you want to
45 # override _swap (if ever), then override overload of '+' and '-', too!
46 # for sub it is a bit tricky to keep b: b-a => -a+b
47 '-'     =>      sub { my $c = $_[0]->copy; $_[2] ?
48                    $c->bneg()->badd($_[1]) :
49                    $c->bsub( $_[1]) },
50 '+'     =>      sub { $_[0]->copy()->badd($_[1]); },
51
52 # some shortcuts for speed (assumes that reversed order of arguments is routed
53 # to normal '+' and we thus can always modify first arg. If this is changed,
54 # this breaks and must be adjusted.)
55 '+='    =>      sub { $_[0]->badd($_[1]); },
56 '-='    =>      sub { $_[0]->bsub($_[1]); },
57 '*='    =>      sub { $_[0]->bmul($_[1]); },
58 '/='    =>      sub { scalar $_[0]->bdiv($_[1]); },
59 '%='    =>      sub { $_[0]->bmod($_[1]); },
60 '^='    =>      sub { $_[0]->bxor($_[1]); },
61 '&='    =>      sub { $_[0]->band($_[1]); },
62 '|='    =>      sub { $_[0]->bior($_[1]); },
63 '**='   =>      sub { $_[0]->bpow($_[1]); },
64
65 # not supported by Perl yet
66 '..'    =>      \&_pointpoint,
67
68 '<=>'   =>      sub { $_[2] ?
69                       ref($_[0])->bcmp($_[1],$_[0]) : 
70                       ref($_[0])->bcmp($_[0],$_[1])},
71 'cmp'   =>      sub {
72          $_[2] ? 
73                "$_[1]" cmp $_[0]->bstr() :
74                $_[0]->bstr() cmp "$_[1]" },
75
76 'log'   =>      sub { $_[0]->copy()->blog(); }, 
77 'int'   =>      sub { $_[0]->copy(); }, 
78 'neg'   =>      sub { $_[0]->copy()->bneg(); }, 
79 'abs'   =>      sub { $_[0]->copy()->babs(); },
80 'sqrt'  =>      sub { $_[0]->copy()->bsqrt(); },
81 '~'     =>      sub { $_[0]->copy()->bnot(); },
82
83 '*'     =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->bmul($a[1]); },
84 '/'     =>      sub { my @a = ref($_[0])->_swap(@_);scalar $a[0]->bdiv($a[1]);},
85 '%'     =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->bmod($a[1]); },
86 '**'    =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->bpow($a[1]); },
87 '<<'    =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->blsft($a[1]); },
88 '>>'    =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->brsft($a[1]); },
89
90 '&'     =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->band($a[1]); },
91 '|'     =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->bior($a[1]); },
92 '^'     =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->bxor($a[1]); },
93
94 # can modify arg of ++ and --, so avoid a new-copy for speed, but don't
95 # use $_[0]->__one(), it modifies $_[0] to be 1!
96 '++'    =>      sub { $_[0]->binc() },
97 '--'    =>      sub { $_[0]->bdec() },
98
99 # if overloaded, O(1) instead of O(N) and twice as fast for small numbers
100 'bool'  =>      sub {
101   # this kludge is needed for perl prior 5.6.0 since returning 0 here fails :-/
102   # v5.6.1 dumps on that: return !$_[0]->is_zero() || undef;                :-(
103   my $t = !$_[0]->is_zero();
104   undef $t if $t == 0;
105   $t;
106   },
107
108 # the original qw() does not work with the TIESCALAR below, why?
109 # Order of arguments unsignificant
110 '""' => sub { $_[0]->bstr(); },
111 '0+' => sub { $_[0]->numify(); }
112 ;
113
114 ##############################################################################
115 # global constants, flags and accessory
116
117 use constant MB_NEVER_ROUND => 0x0001;
118
119 my $NaNOK=1;                            # are NaNs ok?
120 my $nan = 'NaN';                        # constants for easier life
121
122 my $CALC = 'Math::BigInt::Calc';        # module to do low level math
123 my $IMPORT = 0;                         # did import() yet?
124
125 $round_mode = 'even'; # one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'
126 $accuracy   = undef;
127 $precision  = undef;
128 $div_scale  = 40;
129
130 $upgrade = undef;                       # default is no upgrade
131 $downgrade = undef;                     # default is no downgrade
132
133 ##############################################################################
134 # the old code had $rnd_mode, so we need to support it, too
135
136 $rnd_mode   = 'even';
137 sub TIESCALAR  { my ($class) = @_; bless \$round_mode, $class; }
138 sub FETCH      { return $round_mode; }
139 sub STORE      { $rnd_mode = $_[0]->round_mode($_[1]); }
140
141 BEGIN { tie $rnd_mode, 'Math::BigInt'; }
142
143 ############################################################################## 
144
145 sub round_mode
146   {
147   no strict 'refs';
148   # make Class->round_mode() work
149   my $self = shift;
150   my $class = ref($self) || $self || __PACKAGE__;
151   if (defined $_[0])
152     {
153     my $m = shift;
154     die "Unknown round mode $m"
155      if $m !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
156     return ${"${class}::round_mode"} = $m;
157     }
158   return ${"${class}::round_mode"};
159   }
160
161 sub upgrade
162   {
163   no strict 'refs';
164   # make Class->upgrade() work
165   my $self = shift;
166   my $class = ref($self) || $self || __PACKAGE__;
167   # need to set new value?
168   if (@_ > 0)
169     {
170     my $u = shift;
171     return ${"${class}::upgrade"} = $u;
172     }
173   return ${"${class}::upgrade"};
174   }
175
176 sub downgrade
177   {
178   no strict 'refs';
179   # make Class->downgrade() work
180   my $self = shift;
181   my $class = ref($self) || $self || __PACKAGE__;
182   # need to set new value?
183   if (@_ > 0)
184     {
185     my $u = shift;
186     return ${"${class}::downgrade"} = $u;
187     }
188   return ${"${class}::downgrade"};
189   }
190
191 sub div_scale
192   {
193   no strict 'refs';
194   # make Class->round_mode() work
195   my $self = shift;
196   my $class = ref($self) || $self || __PACKAGE__;
197   if (defined $_[0])
198     {
199     die ('div_scale must be greater than zero') if $_[0] < 0;
200     ${"${class}::div_scale"} = shift;
201     }
202   return ${"${class}::div_scale"};
203   }
204
205 sub accuracy
206   {
207   # $x->accuracy($a);           ref($x) $a
208   # $x->accuracy();             ref($x)
209   # Class->accuracy();          class
210   # Class->accuracy($a);        class $a
211
212   my $x = shift;
213   my $class = ref($x) || $x || __PACKAGE__;
214
215   no strict 'refs';
216   # need to set new value?
217   if (@_ > 0)
218     {
219     my $a = shift;
220     die ('accuracy must not be zero') if defined $a && $a == 0;
221     if (ref($x))
222       {
223       # $object->accuracy() or fallback to global
224       $x->bround($a) if defined $a;
225       $x->{_a} = $a;                    # set/overwrite, even if not rounded
226       $x->{_p} = undef;                 # clear P
227       }
228     else
229       {
230       # set global
231       ${"${class}::accuracy"} = $a;
232       ${"${class}::precision"} = undef; # clear P
233       }
234     return $a;                          # shortcut
235     }
236
237   if (ref($x))
238     {
239     # $object->accuracy() or fallback to global
240     return $x->{_a} || ${"${class}::accuracy"};
241     }
242   return ${"${class}::accuracy"};
243   } 
244
245 sub precision
246   {
247   # $x->precision($p);          ref($x) $p
248   # $x->precision();            ref($x)
249   # Class->precision();         class
250   # Class->precision($p);       class $p
251
252   my $x = shift;
253   my $class = ref($x) || $x || __PACKAGE__;
254
255   no strict 'refs';
256   # need to set new value?
257   if (@_ > 0)
258     {
259     my $p = shift;
260     if (ref($x))
261       {
262       # $object->precision() or fallback to global
263       $x->bfround($p) if defined $p;
264       $x->{_p} = $p;                    # set/overwrite, even if not rounded
265       $x->{_a} = undef;                 # clear A
266       }
267     else
268       {
269       # set global
270       ${"${class}::precision"} = $p;
271       ${"${class}::accuracy"} = undef;  # clear A
272       }
273     return $p;                          # shortcut
274     }
275
276   if (ref($x))
277     {
278     # $object->precision() or fallback to global
279     return $x->{_p} || ${"${class}::precision"};
280     }
281   return ${"${class}::precision"};
282   } 
283
284 sub config
285   {
286   # return (later set?) configuration data as hash ref
287   my $class = shift || 'Math::BigInt';
288
289   no strict 'refs';
290   my $lib = $CALC;
291   my $cfg = {
292     lib => $lib,
293     lib_version => ${"${lib}::VERSION"},
294     class => $class,
295     };
296   foreach (
297    qw/upgrade downgrade precision accuracy round_mode VERSION div_scale/)
298     {
299     $cfg->{lc($_)} = ${"${class}::$_"};
300     };
301   $cfg;
302   }
303
304 sub _scale_a
305   { 
306   # select accuracy parameter based on precedence,
307   # used by bround() and bfround(), may return undef for scale (means no op)
308   my ($x,$s,$m,$scale,$mode) = @_;
309   $scale = $x->{_a} if !defined $scale;
310   $scale = $s if (!defined $scale);
311   $mode = $m if !defined $mode;
312   return ($scale,$mode);
313   }
314
315 sub _scale_p
316   { 
317   # select precision parameter based on precedence,
318   # used by bround() and bfround(), may return undef for scale (means no op)
319   my ($x,$s,$m,$scale,$mode) = @_;
320   $scale = $x->{_p} if !defined $scale;
321   $scale = $s if (!defined $scale);
322   $mode = $m if !defined $mode;
323   return ($scale,$mode);
324   }
325
326 ##############################################################################
327 # constructors
328
329 sub copy
330   {
331   my ($c,$x);
332   if (@_ > 1)
333     {
334     # if two arguments, the first one is the class to "swallow" subclasses
335     ($c,$x) = @_;
336     }
337   else
338     {
339     $x = shift;
340     $c = ref($x);
341     }
342   return unless ref($x); # only for objects
343
344   my $self = {}; bless $self,$c;
345   my $r;
346   foreach my $k (keys %$x)
347     {
348     if ($k eq 'value')
349       {
350       $self->{value} = $CALC->_copy($x->{value}); next;
351       }
352     if (!($r = ref($x->{$k})))
353       {
354       $self->{$k} = $x->{$k}; next;
355       }
356     if ($r eq 'SCALAR')
357       {
358       $self->{$k} = \${$x->{$k}};
359       }
360     elsif ($r eq 'ARRAY')
361       {
362       $self->{$k} = [ @{$x->{$k}} ];
363       }
364     elsif ($r eq 'HASH')
365       {
366       # only one level deep!
367       foreach my $h (keys %{$x->{$k}})
368         {
369         $self->{$k}->{$h} = $x->{$k}->{$h};
370         }
371       }
372     else # normal ref
373       {
374       my $xk = $x->{$k};
375       if ($xk->can('copy'))
376         {
377         $self->{$k} = $xk->copy();
378         }
379       else
380         {
381         $self->{$k} = $xk->new($xk);
382         }
383       }
384     }
385   $self;
386   }
387
388 sub new 
389   {
390   # create a new BigInt object from a string or another BigInt object. 
391   # see hash keys documented at top
392
393   # the argument could be an object, so avoid ||, && etc on it, this would
394   # cause costly overloaded code to be called. The only allowed ops are
395   # ref() and defined.
396
397   my ($class,$wanted,$a,$p,$r) = @_;
398  
399   # avoid numify-calls by not using || on $wanted!
400   return $class->bzero($a,$p) if !defined $wanted;      # default to 0
401   return $class->copy($wanted,$a,$p,$r)
402    if ref($wanted) && $wanted->isa($class);             # MBI or subclass
403
404   $class->import() if $IMPORT == 0;             # make require work
405   
406   my $self = bless {}, $class;
407
408   # shortcut for "normal" numbers
409   if ((!ref $wanted) && ($wanted =~ /^([+-]?)[1-9][0-9]*$/))
410     {
411     $self->{sign} = $1 || '+';
412     my $ref = \$wanted;
413     if ($wanted =~ /^[+-]/)
414      {
415       # remove sign without touching wanted
416       my $t = $wanted; $t =~ s/^[+-]//; $ref = \$t;
417       }
418     $self->{value} = $CALC->_new($ref);
419     no strict 'refs';
420     if ( (defined $a) || (defined $p) 
421         || (defined ${"${class}::precision"})
422         || (defined ${"${class}::accuracy"}) 
423        )
424       {
425       $self->round($a,$p,$r) unless (@_ == 4 && !defined $a && !defined $p);
426       }
427     return $self;
428     }
429
430   # handle '+inf', '-inf' first
431   if ($wanted =~ /^[+-]?inf$/)
432     {
433     $self->{value} = $CALC->_zero();
434     $self->{sign} = $wanted; $self->{sign} = '+inf' if $self->{sign} eq 'inf';
435     return $self;
436     }
437   # split str in m mantissa, e exponent, i integer, f fraction, v value, s sign
438   my ($mis,$miv,$mfv,$es,$ev) = _split(\$wanted);
439   if (!ref $mis)
440     {
441     die "$wanted is not a number initialized to $class" if !$NaNOK;
442     #print "NaN 1\n";
443     $self->{value} = $CALC->_zero();
444     $self->{sign} = $nan;
445     return $self;
446     }
447   if (!ref $miv)
448     {
449     # _from_hex or _from_bin
450     $self->{value} = $mis->{value};
451     $self->{sign} = $mis->{sign};
452     return $self;       # throw away $mis
453     }
454   # make integer from mantissa by adjusting exp, then convert to bigint
455   $self->{sign} = $$mis;                        # store sign
456   $self->{value} = $CALC->_zero();              # for all the NaN cases
457   my $e = int("$$es$$ev");                      # exponent (avoid recursion)
458   if ($e > 0)
459     {
460     my $diff = $e - CORE::length($$mfv);
461     if ($diff < 0)                              # Not integer
462       {
463       #print "NOI 1\n";
464       return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
465       $self->{sign} = $nan;
466       }
467     else                                        # diff >= 0
468       {
469       # adjust fraction and add it to value
470       # print "diff > 0 $$miv\n";
471       $$miv = $$miv . ($$mfv . '0' x $diff);
472       }
473     }
474   else
475     {
476     if ($$mfv ne '')                            # e <= 0
477       {
478       # fraction and negative/zero E => NOI
479       #print "NOI 2 \$\$mfv '$$mfv'\n";
480       return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
481       $self->{sign} = $nan;
482       }
483     elsif ($e < 0)
484       {
485       # xE-y, and empty mfv
486       #print "xE-y\n";
487       $e = abs($e);
488       if ($$miv !~ s/0{$e}$//)          # can strip so many zero's?
489         {
490         #print "NOI 3\n";
491         return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
492         $self->{sign} = $nan;
493         }
494       }
495     }
496   $self->{sign} = '+' if $$miv eq '0';                  # normalize -0 => +0
497   $self->{value} = $CALC->_new($miv) if $self->{sign} =~ /^[+-]$/;
498   # if any of the globals is set, use them to round and store them inside $self
499   # do not round for new($x,undef,undef) since that is used by MBF to signal
500   # no rounding
501   $self->round($a,$p,$r) unless @_ == 4 && !defined $a && !defined $p;
502   $self;
503   }
504
505 sub bnan
506   {
507   # create a bigint 'NaN', if given a BigInt, set it to 'NaN'
508   my $self = shift;
509   $self = $class if !defined $self;
510   if (!ref($self))
511     {
512     my $c = $self; $self = {}; bless $self, $c;
513     }
514   $self->import() if $IMPORT == 0;              # make require work
515   return if $self->modify('bnan');
516   my $c = ref($self);
517   if ($self->can('_bnan'))
518     {
519     # use subclass to initialize
520     $self->_bnan();
521     }
522   else
523     {
524     # otherwise do our own thing
525     $self->{value} = $CALC->_zero();
526     }
527   $self->{sign} = $nan;
528   delete $self->{_a}; delete $self->{_p};       # rounding NaN is silly
529   return $self;
530   }
531
532 sub binf
533   {
534   # create a bigint '+-inf', if given a BigInt, set it to '+-inf'
535   # the sign is either '+', or if given, used from there
536   my $self = shift;
537   my $sign = shift; $sign = '+' if !defined $sign || $sign !~ /^-(inf)?$/;
538   $self = $class if !defined $self;
539   if (!ref($self))
540     {
541     my $c = $self; $self = {}; bless $self, $c;
542     }
543   $self->import() if $IMPORT == 0;              # make require work
544   return if $self->modify('binf');
545   my $c = ref($self);
546   if ($self->can('_binf'))
547     {
548     # use subclass to initialize
549     $self->_binf();
550     }
551   else
552     {
553     # otherwise do our own thing
554     $self->{value} = $CALC->_zero();
555     }
556   $sign = $sign . 'inf' if $sign !~ /inf$/;     # - => -inf
557   $self->{sign} = $sign;
558   ($self->{_a},$self->{_p}) = @_;               # take over requested rounding
559   return $self;
560   }
561
562 sub bzero
563   {
564   # create a bigint '+0', if given a BigInt, set it to 0
565   my $self = shift;
566   $self = $class if !defined $self;
567  
568   if (!ref($self))
569     {
570     my $c = $self; $self = {}; bless $self, $c;
571     }
572   $self->import() if $IMPORT == 0;              # make require work
573   return if $self->modify('bzero');
574
575   if ($self->can('_bzero'))
576     {
577     # use subclass to initialize
578     $self->_bzero();
579     }
580   else
581     {
582     # otherwise do our own thing
583     $self->{value} = $CALC->_zero();
584     }
585   $self->{sign} = '+';
586   if (@_ > 0)
587     {
588     $self->{_a} = $_[0]
589      if (defined $self->{_a} && defined $_[0] && $_[0] > $self->{_a});
590     $self->{_p} = $_[1]
591      if (defined $self->{_p} && defined $_[1] && $_[1] < $self->{_p});
592     }
593   return $self;
594   }
595
596 sub bone
597   {
598   # create a bigint '+1' (or -1 if given sign '-'),
599   # if given a BigInt, set it to +1 or -1, respecively
600   my $self = shift;
601   my $sign = shift; $sign = '+' if !defined $sign || $sign ne '-';
602   $self = $class if !defined $self;
603   
604   if (!ref($self))
605     {
606     my $c = $self; $self = {}; bless $self, $c;
607     }
608   $self->import() if $IMPORT == 0;              # make require work
609   return if $self->modify('bone');
610
611   if ($self->can('_bone'))
612     {
613     # use subclass to initialize
614     $self->_bone();
615     }
616   else
617     {
618     # otherwise do our own thing
619     $self->{value} = $CALC->_one();
620     }
621   $self->{sign} = $sign;
622   if (@_ > 0)
623     {
624     $self->{_a} = $_[0]
625      if (defined $self->{_a} && defined $_[0] && $_[0] > $self->{_a});
626     $self->{_p} = $_[1]
627      if (defined $self->{_p} && defined $_[1] && $_[1] < $self->{_p});
628     }
629   return $self;
630   }
631
632 ##############################################################################
633 # string conversation
634
635 sub bsstr
636   {
637   # (ref to BFLOAT or num_str ) return num_str
638   # Convert number from internal format to scientific string format.
639   # internal format is always normalized (no leading zeros, "-0E0" => "+0E0")
640   my $x = shift; $class = ref($x) || $x; $x = $class->new(shift) if !ref($x); 
641   # my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_); 
642
643   if ($x->{sign} !~ /^[+-]$/)
644     {
645     return $x->{sign} unless $x->{sign} eq '+inf';      # -inf, NaN
646     return 'inf';                                       # +inf
647     }
648   my ($m,$e) = $x->parts();
649   # e can only be positive
650   my $sign = 'e+';      
651   # MBF: my $s = $e->{sign}; $s = '' if $s eq '-'; my $sep = 'e'.$s;
652   return $m->bstr().$sign.$e->bstr();
653   }
654
655 sub bstr 
656   {
657   # make a string from bigint object
658   my $x = shift; $class = ref($x) || $x; $x = $class->new(shift) if !ref($x); 
659   # my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_); 
660
661   if ($x->{sign} !~ /^[+-]$/)
662     {
663     return $x->{sign} unless $x->{sign} eq '+inf';      # -inf, NaN
664     return 'inf';                                       # +inf
665     }
666   my $es = ''; $es = $x->{sign} if $x->{sign} eq '-';
667   return $es.${$CALC->_str($x->{value})};
668   }
669
670 sub numify 
671   {
672   # Make a "normal" scalar from a BigInt object
673   my $x = shift; $x = $class->new($x) unless ref $x;
674   return $x->{sign} if $x->{sign} !~ /^[+-]$/;
675   my $num = $CALC->_num($x->{value});
676   return -$num if $x->{sign} eq '-';
677   $num;
678   }
679
680 ##############################################################################
681 # public stuff (usually prefixed with "b")
682
683 sub sign
684   {
685   # return the sign of the number: +/-/-inf/+inf/NaN
686   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_); 
687   
688   $x->{sign};
689   }
690
691 sub _find_round_parameters
692   {
693   # After any operation or when calling round(), the result is rounded by
694   # regarding the A & P from arguments, local parameters, or globals.
695
696   # This procedure finds the round parameters, but it is for speed reasons
697   # duplicated in round. Otherwise, it is tested by the testsuite and used
698   # by fdiv().
699   
700   my ($self,$a,$p,$r,@args) = @_;
701   # $a accuracy, if given by caller
702   # $p precision, if given by caller
703   # $r round_mode, if given by caller
704   # @args all 'other' arguments (0 for unary, 1 for binary ops)
705
706   # leave bigfloat parts alone
707   return ($self) if exists $self->{_f} && $self->{_f} & MB_NEVER_ROUND != 0;
708
709   my $c = ref($self);                           # find out class of argument(s)
710   no strict 'refs';
711
712   # now pick $a or $p, but only if we have got "arguments"
713   if (!defined $a)
714     {
715     foreach ($self,@args)
716       {
717       # take the defined one, or if both defined, the one that is smaller
718       $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
719       }
720     }
721   if (!defined $p)
722     {
723     # even if $a is defined, take $p, to signal error for both defined
724     foreach ($self,@args)
725       {
726       # take the defined one, or if both defined, the one that is bigger
727       # -2 > -3, and 3 > 2
728       $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
729       }
730     }
731   # if still none defined, use globals (#2)
732   $a = ${"$c\::accuracy"} unless defined $a;
733   $p = ${"$c\::precision"} unless defined $p;
734  
735   # no rounding today? 
736   return ($self) unless defined $a || defined $p;               # early out
737
738   # set A and set P is an fatal error
739   return ($self->bnan()) if defined $a && defined $p;
740
741   $r = ${"$c\::round_mode"} unless defined $r;
742   die "Unknown round mode '$r'" if $r !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
743  
744   return ($self,$a,$p,$r);
745   }
746
747 sub round
748   {
749   # Round $self according to given parameters, or given second argument's
750   # parameters or global defaults 
751
752   # for speed reasons, _find_round_parameters is embeded here:
753
754   my ($self,$a,$p,$r,@args) = @_;
755   # $a accuracy, if given by caller
756   # $p precision, if given by caller
757   # $r round_mode, if given by caller
758   # @args all 'other' arguments (0 for unary, 1 for binary ops)
759
760   # leave bigfloat parts alone
761   return ($self) if exists $self->{_f} && $self->{_f} & MB_NEVER_ROUND != 0;
762
763   my $c = ref($self);                           # find out class of argument(s)
764   no strict 'refs';
765
766   # now pick $a or $p, but only if we have got "arguments"
767   if (!defined $a)
768     {
769     foreach ($self,@args)
770       {
771       # take the defined one, or if both defined, the one that is smaller
772       $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
773       }
774     }
775   if (!defined $p)
776     {
777     # even if $a is defined, take $p, to signal error for both defined
778     foreach ($self,@args)
779       {
780       # take the defined one, or if both defined, the one that is bigger
781       # -2 > -3, and 3 > 2
782       $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
783       }
784     }
785   # if still none defined, use globals (#2)
786   $a = ${"$c\::accuracy"} unless defined $a;
787   $p = ${"$c\::precision"} unless defined $p;
788  
789   # no rounding today? 
790   return $self unless defined $a || defined $p;         # early out
791
792   # set A and set P is an fatal error
793   return $self->bnan() if defined $a && defined $p;
794
795   $r = ${"$c\::round_mode"} unless defined $r;
796   die "Unknown round mode '$r'" if $r !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
797
798   # now round, by calling either fround or ffround:
799   if (defined $a)
800     {
801     $self->bround($a,$r) if !defined $self->{_a} || $self->{_a} >= $a;
802     }
803   else # both can't be undefined due to early out
804     {
805     $self->bfround($p,$r) if !defined $self->{_p} || $self->{_p} <= $p;
806     }
807   $self->bnorm();                       # after round, normalize
808   }
809
810 sub bnorm
811   { 
812   # (numstr or BINT) return BINT
813   # Normalize number -- no-op here
814   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
815   $x;
816   }
817
818 sub babs 
819   {
820   # (BINT or num_str) return BINT
821   # make number absolute, or return absolute BINT from string
822   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
823
824   return $x if $x->modify('babs');
825   # post-normalized abs for internal use (does nothing for NaN)
826   $x->{sign} =~ s/^-/+/;
827   $x;
828   }
829
830 sub bneg 
831   { 
832   # (BINT or num_str) return BINT
833   # negate number or make a negated number from string
834   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
835   
836   return $x if $x->modify('bneg');
837
838   # for +0 dont negate (to have always normalized)
839   $x->{sign} =~ tr/+-/-+/ if !$x->is_zero();    # does nothing for NaN
840   $x;
841   }
842
843 sub bcmp 
844   {
845   # Compares 2 values.  Returns one of undef, <0, =0, >0. (suitable for sort)
846   # (BINT or num_str, BINT or num_str) return cond_code
847   my ($self,$x,$y) = objectify(2,@_);
848
849   if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
850     {
851     # handle +-inf and NaN
852     return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
853     return 0 if $x->{sign} eq $y->{sign} && $x->{sign} =~ /^[+-]inf$/;
854     return +1 if $x->{sign} eq '+inf';
855     return -1 if $x->{sign} eq '-inf';
856     return -1 if $y->{sign} eq '+inf';
857     return +1;
858     }
859   # check sign for speed first
860   return 1 if $x->{sign} eq '+' && $y->{sign} eq '-';   # does also 0 <=> -y
861   return -1 if $x->{sign} eq '-' && $y->{sign} eq '+';  # does also -x <=> 0 
862
863   # shortcut
864   my $xz = $x->is_zero();
865   my $yz = $y->is_zero();
866   return 0 if $xz && $yz;                               # 0 <=> 0
867   return -1 if $xz && $y->{sign} eq '+';                # 0 <=> +y
868   return 1 if $yz && $x->{sign} eq '+';                 # +x <=> 0
869   
870   # post-normalized compare for internal use (honors signs)
871   if ($x->{sign} eq '+') 
872     {
873     # $x and $y both > 0
874     return $CALC->_acmp($x->{value},$y->{value});
875     }
876
877   # $x && $y both < 0
878   $CALC->_acmp($y->{value},$x->{value});        # swaped (lib does only 0,1,-1)
879   }
880
881 sub bacmp 
882   {
883   # Compares 2 values, ignoring their signs. 
884   # Returns one of undef, <0, =0, >0. (suitable for sort)
885   # (BINT, BINT) return cond_code
886   my ($self,$x,$y) = objectify(2,@_);
887   
888   if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
889     {
890     # handle +-inf and NaN
891     return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
892     return 0 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} =~ /^[+-]inf$/;
893     return +1;  # inf is always bigger
894     }
895   $CALC->_acmp($x->{value},$y->{value});        # lib does only 0,1,-1
896   }
897
898 sub badd 
899   {
900   # add second arg (BINT or string) to first (BINT) (modifies first)
901   # return result as BINT
902   my ($self,$x,$y,@r) = objectify(2,@_);
903
904   return $x if $x->modify('badd');
905   return $upgrade->badd($x,$y,@r) if defined $upgrade &&
906     ((!$x->isa($self)) || (!$y->isa($self)));
907
908   $r[3] = $y;                           # no push!
909   # inf and NaN handling
910   if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
911     {
912     # NaN first
913     return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
914     # inf handling
915     if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
916       {
917       # +inf++inf or -inf+-inf => same, rest is NaN
918       return $x if $x->{sign} eq $y->{sign};
919       return $x->bnan();
920       }
921     # +-inf + something => +inf
922     # something +-inf => +-inf
923     $x->{sign} = $y->{sign}, return $x if $y->{sign} =~ /^[+-]inf$/;
924     return $x;
925     }
926     
927   my ($sx, $sy) = ( $x->{sign}, $y->{sign} ); # get signs
928
929   if ($sx eq $sy)  
930     {
931     $x->{value} = $CALC->_add($x->{value},$y->{value}); # same sign, abs add
932     $x->{sign} = $sx;
933     }
934   else 
935     {
936     my $a = $CALC->_acmp ($y->{value},$x->{value});     # absolute compare
937     if ($a > 0)                           
938       {
939       #print "swapped sub (a=$a)\n";
940       $x->{value} = $CALC->_sub($y->{value},$x->{value},1); # abs sub w/ swap
941       $x->{sign} = $sy;
942       } 
943     elsif ($a == 0)
944       {
945       # speedup, if equal, set result to 0
946       #print "equal sub, result = 0\n";
947       $x->{value} = $CALC->_zero();
948       $x->{sign} = '+';
949       }
950     else # a < 0
951       {
952       #print "unswapped sub (a=$a)\n";
953       $x->{value} = $CALC->_sub($x->{value}, $y->{value}); # abs sub
954       $x->{sign} = $sx;
955       }
956     }
957   $x->round(@r);
958   }
959
960 sub bsub 
961   {
962   # (BINT or num_str, BINT or num_str) return num_str
963   # subtract second arg from first, modify first
964   my ($self,$x,$y,@r) = objectify(2,@_);
965
966   return $x if $x->modify('bsub');
967
968 # upgrade done by badd():
969 #  return $upgrade->badd($x,$y,@r) if defined $upgrade &&
970 #   ((!$x->isa($self)) || (!$y->isa($self)));
971
972   if ($y->is_zero())
973     { 
974     return $x->round(@r);
975     }
976
977   $y->{sign} =~ tr/+\-/-+/;     # does nothing for NaN
978   $x->badd($y,@r);              # badd does not leave internal zeros
979   $y->{sign} =~ tr/+\-/-+/;     # refix $y (does nothing for NaN)
980   $x;                           # already rounded by badd() or no round necc.
981   }
982
983 sub binc
984   {
985   # increment arg by one
986   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
987   return $x if $x->modify('binc');
988
989   if ($x->{sign} eq '+')
990     {
991     $x->{value} = $CALC->_inc($x->{value});
992     return $x->round($a,$p,$r);
993     }
994   elsif ($x->{sign} eq '-')
995     {
996     $x->{value} = $CALC->_dec($x->{value});
997     $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # -1 +1 => -0 => +0
998     return $x->round($a,$p,$r);
999     }
1000   # inf, nan handling etc
1001   $x->badd($self->__one(),$a,$p,$r);            # badd does round
1002   }
1003
1004 sub bdec
1005   {
1006   # decrement arg by one
1007   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1008   return $x if $x->modify('bdec');
1009   
1010   my $zero = $CALC->_is_zero($x->{value}) && $x->{sign} eq '+';
1011   # <= 0
1012   if (($x->{sign} eq '-') || $zero) 
1013     {
1014     $x->{value} = $CALC->_inc($x->{value});
1015     $x->{sign} = '-' if $zero;                  # 0 => 1 => -1
1016     $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # -1 +1 => -0 => +0
1017     return $x->round($a,$p,$r);
1018     }
1019   # > 0
1020   elsif ($x->{sign} eq '+')
1021     {
1022     $x->{value} = $CALC->_dec($x->{value});
1023     return $x->round($a,$p,$r);
1024     }
1025   # inf, nan handling etc
1026   $x->badd($self->__one('-'),$a,$p,$r);                 # badd does round
1027   } 
1028
1029 sub blog
1030   {
1031   # not implemented yet
1032   my ($self,$x,$base,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1033  
1034   return $upgrade->blog($x,$base,$a,$p,$r) if defined $upgrade;
1035
1036   return $x->bnan();
1037   }
1038  
1039 sub blcm 
1040   { 
1041   # (BINT or num_str, BINT or num_str) return BINT
1042   # does not modify arguments, but returns new object
1043   # Lowest Common Multiplicator
1044
1045   my $y = shift; my ($x);
1046   if (ref($y))
1047     {
1048     $x = $y->copy();
1049     }
1050   else
1051     {
1052     $x = $class->new($y);
1053     }
1054   while (@_) { $x = __lcm($x,shift); } 
1055   $x;
1056   }
1057
1058 sub bgcd 
1059   { 
1060   # (BINT or num_str, BINT or num_str) return BINT
1061   # does not modify arguments, but returns new object
1062   # GCD -- Euclids algorithm, variant C (Knuth Vol 3, pg 341 ff)
1063
1064   my $y = shift;
1065   $y = __PACKAGE__->new($y) if !ref($y);
1066   my $self = ref($y);
1067   my $x = $y->copy();           # keep arguments
1068   if ($CALC->can('_gcd'))
1069     {
1070     while (@_)
1071       {
1072       $y = shift; $y = $self->new($y) if !ref($y);
1073       next if $y->is_zero();
1074       return $x->bnan() if $y->{sign} !~ /^[+-]$/;      # y NaN?
1075       $x->{value} = $CALC->_gcd($x->{value},$y->{value}); last if $x->is_one();
1076       }
1077     }
1078   else
1079     {
1080     while (@_)
1081       {
1082       $y = shift; $y = $self->new($y) if !ref($y);
1083       $x = __gcd($x,$y->copy()); last if $x->is_one();  # _gcd handles NaN
1084       } 
1085     }
1086   $x->babs();
1087   }
1088
1089 sub bnot 
1090   {
1091   # (num_str or BINT) return BINT
1092   # represent ~x as twos-complement number
1093   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1094   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
1095  
1096   return $x if $x->modify('bnot');
1097   $x->bneg()->bdec();                   # bdec already does round
1098   }
1099
1100 # is_foo test routines
1101
1102 sub is_zero
1103   {
1104   # return true if arg (BINT or num_str) is zero (array '+', '0')
1105   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1106   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1107   
1108   return 0 if $x->{sign} !~ /^\+$/;                     # -, NaN & +-inf aren't
1109   $CALC->_is_zero($x->{value});
1110   }
1111
1112 sub is_nan
1113   {
1114   # return true if arg (BINT or num_str) is NaN
1115   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1116
1117   return 1 if $x->{sign} eq $nan;
1118   0;
1119   }
1120
1121 sub is_inf
1122   {
1123   # return true if arg (BINT or num_str) is +-inf
1124   my ($self,$x,$sign) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1125
1126   $sign = '' if !defined $sign;
1127   return 1 if $sign eq $x->{sign};              # match ("+inf" eq "+inf")
1128   return 0 if $sign !~ /^([+-]|)$/;
1129
1130   if ($sign eq '')
1131     {
1132     return 1 if ($x->{sign} =~ /^[+-]inf$/); 
1133     return 0;
1134     }
1135   $sign = quotemeta($sign.'inf');
1136   return 1 if ($x->{sign} =~ /^$sign$/);
1137   0;
1138   }
1139
1140 sub is_one
1141   {
1142   # return true if arg (BINT or num_str) is +1
1143   # or -1 if sign is given
1144   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1145   my ($self,$x,$sign) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
1146     
1147   $sign = '' if !defined $sign; $sign = '+' if $sign ne '-';
1148  
1149   return 0 if $x->{sign} ne $sign;      # -1 != +1, NaN, +-inf aren't either
1150   $CALC->_is_one($x->{value});
1151   }
1152
1153 sub is_odd
1154   {
1155   # return true when arg (BINT or num_str) is odd, false for even
1156   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1157   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1158
1159   return 0 if $x->{sign} !~ /^[+-]$/;                   # NaN & +-inf aren't
1160   $CALC->_is_odd($x->{value});
1161   }
1162
1163 sub is_even
1164   {
1165   # return true when arg (BINT or num_str) is even, false for odd
1166   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1167   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1168
1169   return 0 if $x->{sign} !~ /^[+-]$/;                   # NaN & +-inf aren't
1170   $CALC->_is_even($x->{value});
1171   }
1172
1173 sub is_positive
1174   {
1175   # return true when arg (BINT or num_str) is positive (>= 0)
1176   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1177   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1178   
1179   return 1 if $x->{sign} =~ /^\+/;
1180   0;
1181   }
1182
1183 sub is_negative
1184   {
1185   # return true when arg (BINT or num_str) is negative (< 0)
1186   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1187   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1188   
1189   return 1 if ($x->{sign} =~ /^-/);
1190   0;
1191   }
1192
1193 sub is_int
1194   {
1195   # return true when arg (BINT or num_str) is an integer
1196   # always true for BigInt, but different for Floats
1197   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1198   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1199   
1200   $x->{sign} =~ /^[+-]$/ ? 1 : 0;               # inf/-inf/NaN aren't
1201   }
1202
1203 ###############################################################################
1204
1205 sub bmul 
1206   { 
1207   # multiply two numbers -- stolen from Knuth Vol 2 pg 233
1208   # (BINT or num_str, BINT or num_str) return BINT
1209   my ($self,$x,$y,@r) = objectify(2,@_);
1210   
1211   return $x if $x->modify('bmul');
1212
1213   return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1214
1215   # inf handling
1216   if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/))
1217     {
1218     return $x->bnan() if $x->is_zero() || $y->is_zero();
1219     # result will always be +-inf:
1220     # +inf * +/+inf => +inf, -inf * -/-inf => +inf
1221     # +inf * -/-inf => -inf, -inf * +/+inf => -inf
1222     return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/); 
1223     return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/); 
1224     return $x->binf('-');
1225     }
1226   
1227   return $upgrade->bmul($x,$y,@r)
1228    if defined $upgrade && $y->isa($upgrade);
1229   
1230   $r[3] = $y;                           # no push here
1231
1232   $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => +
1233
1234   $x->{value} = $CALC->_mul($x->{value},$y->{value});   # do actual math
1235   $x->{sign} = '+' if $CALC->_is_zero($x->{value});     # no -0
1236   $x->round(@r);
1237   }
1238
1239 sub _div_inf
1240   {
1241   # helper function that handles +-inf cases for bdiv()/bmod() to reuse code
1242   my ($self,$x,$y) = @_;
1243
1244   # NaN if x == NaN or y == NaN or x==y==0
1245   return wantarray ? ($x->bnan(),$self->bnan()) : $x->bnan()
1246    if (($x->is_nan() || $y->is_nan())   ||
1247        ($x->is_zero() && $y->is_zero()));
1248  
1249   # +-inf / +-inf == NaN, reminder also NaN
1250   if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
1251     {
1252     return wantarray ? ($x->bnan(),$self->bnan()) : $x->bnan();
1253     }
1254   # x / +-inf => 0, remainder x (works even if x == 0)
1255   if ($y->{sign} =~ /^[+-]inf$/)
1256     {
1257     my $t = $x->copy();         # binf clobbers up $x
1258     return wantarray ? ($x->bzero(),$t) : $x->bzero()
1259     }
1260   
1261   # 5 / 0 => +inf, -6 / 0 => -inf
1262   # +inf / 0 = inf, inf,  and -inf / 0 => -inf, -inf 
1263   # exception:   -8 / 0 has remainder -8, not 8
1264   # exception: -inf / 0 has remainder -inf, not inf
1265   if ($y->is_zero())
1266     {
1267     # +-inf / 0 => special case for -inf
1268     return wantarray ?  ($x,$x->copy()) : $x if $x->is_inf();
1269     if (!$x->is_zero() && !$x->is_inf())
1270       {
1271       my $t = $x->copy();               # binf clobbers up $x
1272       return wantarray ?
1273        ($x->binf($x->{sign}),$t) : $x->binf($x->{sign})
1274       }
1275     }
1276   
1277   # last case: +-inf / ordinary number
1278   my $sign = '+inf';
1279   $sign = '-inf' if substr($x->{sign},0,1) ne $y->{sign};
1280   $x->{sign} = $sign;
1281   return wantarray ? ($x,$self->bzero()) : $x;
1282   }
1283
1284 sub bdiv 
1285   {
1286   # (dividend: BINT or num_str, divisor: BINT or num_str) return 
1287   # (BINT,BINT) (quo,rem) or BINT (only rem)
1288   my ($self,$x,$y,@r) = objectify(2,@_);
1289
1290   return $x if $x->modify('bdiv');
1291
1292   return $self->_div_inf($x,$y)
1293    if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero());
1294
1295   #print "mbi bdiv $x $y\n";
1296   return $upgrade->bdiv($upgrade->new($x),$y,@r)
1297    if defined $upgrade && !$y->isa($self);
1298
1299   $r[3] = $y;                                   # no push!
1300
1301   # 0 / something
1302   return
1303    wantarray ? ($x->round(@r),$self->bzero(@r)):$x->round(@r) if $x->is_zero();
1304  
1305   # Is $x in the interval [0, $y) (aka $x <= $y) ?
1306   my $cmp = $CALC->_acmp($x->{value},$y->{value});
1307   if (($cmp < 0) and (($x->{sign} eq $y->{sign}) or !wantarray))
1308     {
1309     return $upgrade->bdiv($upgrade->new($x),$upgrade->new($y),@r)
1310      if defined $upgrade;
1311
1312     return $x->bzero()->round(@r) unless wantarray;
1313     my $t = $x->copy();      # make copy first, because $x->bzero() clobbers $x
1314     return ($x->bzero()->round(@r),$t);
1315     }
1316   elsif ($cmp == 0)
1317     {
1318     # shortcut, both are the same, so set to +/- 1
1319     $x->__one( ($x->{sign} ne $y->{sign} ? '-' : '+') ); 
1320     return $x unless wantarray;
1321     return ($x->round(@r),$self->bzero(@r));
1322     }
1323   return $upgrade->bdiv($upgrade->new($x),$upgrade->new($y),@r)
1324    if defined $upgrade;
1325    
1326   # calc new sign and in case $y == +/- 1, return $x
1327   my $xsign = $x->{sign};                               # keep
1328   $x->{sign} = ($x->{sign} ne $y->{sign} ? '-' : '+'); 
1329   # check for / +-1 (cant use $y->is_one due to '-'
1330   if ($CALC->_is_one($y->{value}))
1331     {
1332     return wantarray ? ($x->round(@r),$self->bzero(@r)) : $x->round(@r); 
1333     }
1334
1335   if (wantarray)
1336     {
1337     my $rem = $self->bzero(); 
1338     ($x->{value},$rem->{value}) = $CALC->_div($x->{value},$y->{value});
1339     $x->{sign} = '+' if $CALC->_is_zero($x->{value});
1340     $x->round(@r); 
1341     if (! $CALC->_is_zero($rem->{value}))
1342       {
1343       $rem->{sign} = $y->{sign};
1344       $rem = $y-$rem if $xsign ne $y->{sign};   # one of them '-'
1345       }
1346     else
1347       {
1348       $rem->{sign} = '+';                       # dont leave -0
1349       }
1350     $rem->round(@r);
1351     return ($x,$rem);
1352     }
1353
1354   $x->{value} = $CALC->_div($x->{value},$y->{value});
1355   $x->{sign} = '+' if $CALC->_is_zero($x->{value});
1356   $x->round(@r); 
1357   }
1358
1359 ###############################################################################
1360 # modulus functions
1361
1362 sub bmod 
1363   {
1364   # modulus (or remainder)
1365   # (BINT or num_str, BINT or num_str) return BINT
1366   my ($self,$x,$y,@r) = objectify(2,@_);
1367
1368   return $x if $x->modify('bmod');
1369   $r[3] = $y;                                   # no push!
1370   if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero())
1371     {
1372     my ($d,$r) = $self->_div_inf($x,$y);
1373     return $r->round(@r);
1374     }
1375
1376   if ($CALC->can('_mod'))
1377     {
1378     # calc new sign and in case $y == +/- 1, return $x
1379     $x->{value} = $CALC->_mod($x->{value},$y->{value});
1380     if (!$CALC->_is_zero($x->{value}))
1381       {
1382       my $xsign = $x->{sign};
1383       $x->{sign} = $y->{sign};
1384       $x = $y-$x if $xsign ne $y->{sign};       # one of them '-'
1385       }
1386     else
1387       {
1388       $x->{sign} = '+';                         # dont leave -0
1389       }
1390     return $x->round(@r);
1391     }
1392   my ($t,$rem) = $self->bdiv($x->copy(),$y,@r); # slow way (also rounds)
1393   # modify in place
1394   foreach (qw/value sign _a _p/)
1395     {
1396     $x->{$_} = $rem->{$_};
1397     }
1398   $x;
1399   }
1400
1401 sub bmodinv_not_yet_implemented
1402   {
1403   # modular inverse.  given a number which is (hopefully) relatively
1404   # prime to the modulus, calculate its inverse using Euclid's
1405   # alogrithm.  if the number is not relatively prime to the modulus
1406   # (i.e. their gcd is not one) then NaN is returned.
1407
1408   my ($self,$num,$mod,@r) = objectify(2,@_);
1409
1410   return $num if $num->modify('bmodinv');
1411
1412   return $num->bnan()
1413         if ($mod->{sign} ne '+'                         # -, NaN, +inf, -inf
1414          || $num->is_zero()                             # or num == 0
1415          || $num->{sign} !~ /^[+-]$/                    # or num NaN, inf, -inf
1416         );
1417 #  return $num                        # i.e., NaN or some kind of infinity,
1418 #      if ($num->{sign} =~ /\w/);
1419
1420   # the remaining case, nonpositive case, $num < 0, is addressed below.
1421
1422   my ($u, $u1) = ($self->bzero(), $self->bone());
1423   my ($a, $b) = ($mod->copy(), $num->copy());
1424
1425   # put least residue into $b if $num was negative
1426   $b %= $mod if $b->{sign} eq '-';
1427
1428     # Euclid's Algorithm
1429     while( ! $b->is_zero()) {
1430       ($a, my $q, $b) = ($b, $self->bdiv( $a->copy(), $b));
1431       ($u, $u1) = ($u1, $u - $u1 * $q);
1432     }
1433
1434     # if the gcd is not 1, then return NaN!  It would be pointless to
1435     # have called bgcd first, because we would then be performing the
1436     # same Euclidean Algorithm *twice*
1437     return $self->bnan() unless $a->is_one();
1438
1439     $u %= $mod;
1440     return $u;
1441   }
1442
1443 sub bmodpow_not_yet_implemented
1444   {
1445   # takes a very large number to a very large exponent in a given very
1446   # large modulus, quickly, thanks to binary exponentation.  supports
1447   # negative exponents.
1448   my ($self,$num,$exp,$mod,@r) = objectify(3,@_);
1449
1450   return $num if $num->modify('bmodpow');
1451
1452   # check modulus for valid values
1453   return $num->bnan() if ($mod->{sign} ne '+'           # NaN, - , -inf, +inf
1454                        || $mod->is_zero());
1455
1456   # check exponent for valid values
1457   if ($exp->{sign} =~ /\w/) 
1458     {
1459     # i.e., if it's NaN, +inf, or -inf...
1460     return $num->bnan();
1461     }
1462   elsif ($exp->{sign} eq '-')
1463     {
1464     $exp->babs();
1465     $num->bmodinv ($mod);
1466     return $num if $num->{sign} !~ /^[+-]/;     # i.e. if there was no inverse
1467     }
1468
1469     # check num for valid values
1470     return $num->bnan() if $num->{sign} !~ /^[+-]$/;
1471
1472     # in the trivial case,
1473     return $num->bzero() if $mod->is_one();
1474     return $num->bone() if $num->is_zero() or $num->is_one();
1475
1476     my $acc = $num->copy(); $num->bone();       # keep ref to $num
1477
1478       print "$num $acc $exp\n"; 
1479     while( !$exp->is_zero() ) {
1480       if( $exp->is_odd() ) {
1481        $num->bmul($acc)->bmod($mod);
1482       }
1483       $acc->bmul($acc)->bmod($mod);
1484       $exp->brsft( 1, 2);               # remove last (binary) digit
1485       print "$num $acc $exp\n"; 
1486     }
1487   return $num;
1488   }
1489
1490 ###############################################################################
1491
1492 sub bfac
1493   {
1494   # (BINT or num_str, BINT or num_str) return BINT
1495   # compute factorial numbers
1496   # modifies first argument
1497   my ($self,$x,@r) = objectify(1,@_);
1498
1499   return $x if $x->modify('bfac');
1500  
1501   return $x->bnan() if $x->{sign} ne '+';       # inf, NnN, <0 etc => NaN
1502   return $x->bone(@r) if $x->is_zero() || $x->is_one();         # 0 or 1 => 1
1503
1504   if ($CALC->can('_fac'))
1505     {
1506     $x->{value} = $CALC->_fac($x->{value});
1507     return $x->round(@r);
1508     }
1509
1510   my $n = $x->copy();
1511   $x->bone();
1512   my $f = $self->new(2);
1513   while ($f->bacmp($n) < 0)
1514     {
1515     $x->bmul($f); $f->binc();
1516     }
1517   $x->bmul($f);                                 # last step
1518   $x->round(@r);                                # round
1519   }
1520  
1521 sub bpow 
1522   {
1523   # (BINT or num_str, BINT or num_str) return BINT
1524   # compute power of two numbers -- stolen from Knuth Vol 2 pg 233
1525   # modifies first argument
1526   my ($self,$x,$y,@r) = objectify(2,@_);
1527
1528   return $x if $x->modify('bpow');
1529
1530   return $upgrade->bpow($upgrade->new($x),$y,@r)
1531    if defined $upgrade && !$y->isa($self);
1532
1533   $r[3] = $y;                                   # no push!
1534   return $x if $x->{sign} =~ /^[+-]inf$/;       # -inf/+inf ** x
1535   return $x->bnan() if $x->{sign} eq $nan || $y->{sign} eq $nan;
1536   return $x->bone(@r) if $y->is_zero();
1537   return $x->round(@r) if $x->is_one() || $y->is_one();
1538   if ($x->{sign} eq '-' && $CALC->_is_one($x->{value}))
1539     {
1540     # if $x == -1 and odd/even y => +1/-1
1541     return $y->is_odd() ? $x->round(@r) : $x->babs()->round(@r);
1542     # my Casio FX-5500L has a bug here: -1 ** 2 is -1, but -1 * -1 is 1;
1543     }
1544   # 1 ** -y => 1 / (1 ** |y|)
1545   # so do test for negative $y after above's clause
1546   return $x->bnan() if $y->{sign} eq '-';
1547   return $x->round(@r) if $x->is_zero();  # 0**y => 0 (if not y <= 0)
1548
1549   if ($CALC->can('_pow'))
1550     {
1551     $x->{value} = $CALC->_pow($x->{value},$y->{value});
1552     return $x->round(@r);
1553     }
1554
1555 # based on the assumption that shifting in base 10 is fast, and that mul
1556 # works faster if numbers are small: we count trailing zeros (this step is
1557 # O(1)..O(N), but in case of O(N) we save much more time due to this),
1558 # stripping them out of the multiplication, and add $count * $y zeros
1559 # afterwards like this:
1560 # 300 ** 3 == 300*300*300 == 3*3*3 . '0' x 2 * 3 == 27 . '0' x 6
1561 # creates deep recursion?
1562 #  my $zeros = $x->_trailing_zeros();
1563 #  if ($zeros > 0)
1564 #    {
1565 #    $x->brsft($zeros,10);      # remove zeros
1566 #    $x->bpow($y);              # recursion (will not branch into here again)
1567 #    $zeros = $y * $zeros;      # real number of zeros to add
1568 #    $x->blsft($zeros,10);
1569 #    return $x->round($a,$p,$r);
1570 #    }
1571
1572   my $pow2 = $self->__one();
1573   my $y1 = $class->new($y);
1574   my $two = $self->new(2);
1575   while (!$y1->is_one())
1576     {
1577     $pow2->bmul($x) if $y1->is_odd();
1578     $y1->bdiv($two);
1579     $x->bmul($x);
1580     }
1581   $x->bmul($pow2) unless $pow2->is_one();
1582   $x->round(@r);
1583   }
1584
1585 sub blsft 
1586   {
1587   # (BINT or num_str, BINT or num_str) return BINT
1588   # compute x << y, base n, y >= 0
1589   my ($self,$x,$y,$n,$a,$p,$r) = objectify(2,@_);
1590   
1591   return $x if $x->modify('blsft');
1592   return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1593   return $x->round($a,$p,$r) if $y->is_zero();
1594
1595   $n = 2 if !defined $n; return $x->bnan() if $n <= 0 || $y->{sign} eq '-';
1596
1597   my $t; $t = $CALC->_lsft($x->{value},$y->{value},$n) if $CALC->can('_lsft');
1598   if (defined $t)
1599     {
1600     $x->{value} = $t; return $x->round($a,$p,$r);
1601     }
1602   # fallback
1603   return $x->bmul( $self->bpow($n, $y, $a, $p, $r), $a, $p, $r );
1604   }
1605
1606 sub brsft 
1607   {
1608   # (BINT or num_str, BINT or num_str) return BINT
1609   # compute x >> y, base n, y >= 0
1610   my ($self,$x,$y,$n,$a,$p,$r) = objectify(2,@_);
1611
1612   return $x if $x->modify('brsft');
1613   return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1614   return $x->round($a,$p,$r) if $y->is_zero();
1615   return $x->bzero($a,$p,$r) if $x->is_zero();          # 0 => 0
1616
1617   $n = 2 if !defined $n; return $x->bnan() if $n <= 0 || $y->{sign} eq '-';
1618
1619    # this only works for negative numbers when shifting in base 2
1620   if (($x->{sign} eq '-') && ($n == 2))
1621     {
1622     return $x->round($a,$p,$r) if $x->is_one('-');      # -1 => -1
1623     if (!$y->is_one())
1624       {
1625       # although this is O(N*N) in calc (as_bin!) it is O(N) in Pari et al
1626       # but perhaps there is a better emulation for two's complement shift...
1627       # if $y != 1, we must simulate it by doing:
1628       # convert to bin, flip all bits, shift, and be done
1629       $x->binc();                       # -3 => -2
1630       my $bin = $x->as_bin();
1631       $bin =~ s/^-0b//;                 # strip '-0b' prefix
1632       $bin =~ tr/10/01/;                # flip bits
1633       # now shift
1634       if (CORE::length($bin) <= $y)
1635         {
1636         $bin = '0';                     # shifting to far right creates -1
1637                                         # 0, because later increment makes 
1638                                         # that 1, attached '-' makes it '-1'
1639                                         # because -1 >> x == -1 !
1640         } 
1641       else
1642         {
1643         $bin =~ s/.{$y}$//;             # cut off at the right side
1644         $bin = '1' . $bin;              # extend left side by one dummy '1'
1645         $bin =~ tr/10/01/;              # flip bits back
1646         }
1647       my $res = $self->new('0b'.$bin);  # add prefix and convert back
1648       $res->binc();                     # remember to increment
1649       $x->{value} = $res->{value};      # take over value
1650       return $x->round($a,$p,$r);       # we are done now, magic, isn't?
1651       }
1652     $x->bdec();                         # n == 2, but $y == 1: this fixes it
1653     }
1654
1655   my $t; $t = $CALC->_rsft($x->{value},$y->{value},$n) if $CALC->can('_rsft');
1656   if (defined $t)
1657     {
1658     $x->{value} = $t;
1659     return $x->round($a,$p,$r);
1660     }
1661   # fallback
1662   $x->bdiv($self->bpow($n,$y, $a,$p,$r), $a,$p,$r);
1663   $x;
1664   }
1665
1666 sub band 
1667   {
1668   #(BINT or num_str, BINT or num_str) return BINT
1669   # compute x & y
1670   my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1671   
1672   return $x if $x->modify('band');
1673
1674   local $Math::BigInt::upgrade = undef;
1675
1676   return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1677   return $x->bzero() if $y->is_zero() || $x->is_zero();
1678
1679   my $sign = 0;                                 # sign of result
1680   $sign = 1 if ($x->{sign} eq '-') && ($y->{sign} eq '-');
1681   my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1682   my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1683   
1684   if ($CALC->can('_and') && $sx == 1 && $sy == 1)
1685     {
1686     $x->{value} = $CALC->_and($x->{value},$y->{value});
1687     return $x->round($a,$p,$r);
1688     }
1689
1690   my $m = $self->bone(); my ($xr,$yr);
1691   my $x10000 = $self->new (0x1000);
1692   my $y1 = copy(ref($x),$y);                    # make copy
1693   $y1->babs();                                  # and positive
1694   my $x1 = $x->copy()->babs(); $x->bzero();     # modify x in place!
1695   use integer;                                  # need this for negative bools
1696   while (!$x1->is_zero() && !$y1->is_zero())
1697     {
1698     ($x1, $xr) = bdiv($x1, $x10000);
1699     ($y1, $yr) = bdiv($y1, $x10000);
1700     # make both op's numbers!
1701     $x->badd( bmul( $class->new(
1702        abs($sx*int($xr->numify()) & $sy*int($yr->numify()))), 
1703       $m));
1704     $m->bmul($x10000);
1705     }
1706   $x->bneg() if $sign;
1707   return $x->round($a,$p,$r);
1708   }
1709
1710 sub bior 
1711   {
1712   #(BINT or num_str, BINT or num_str) return BINT
1713   # compute x | y
1714   my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1715
1716   return $x if $x->modify('bior');
1717
1718   local $Math::BigInt::upgrade = undef;
1719
1720   return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1721   return $x if $y->is_zero();
1722
1723   my $sign = 0;                                 # sign of result
1724   $sign = 1 if ($x->{sign} eq '-') || ($y->{sign} eq '-');
1725   my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1726   my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1727
1728   # don't use lib for negative values
1729   if ($CALC->can('_or') && $sx == 1 && $sy == 1)
1730     {
1731     $x->{value} = $CALC->_or($x->{value},$y->{value});
1732     return $x->round($a,$p,$r);
1733     }
1734
1735   my $m = $self->bone(); my ($xr,$yr);
1736   my $x10000 = $self->new(0x10000);
1737   my $y1 = copy(ref($x),$y);                    # make copy
1738   $y1->babs();                                  # and positive
1739   my $x1 = $x->copy()->babs(); $x->bzero();     # modify x in place!
1740   use integer;                                  # need this for negative bools
1741   while (!$x1->is_zero() || !$y1->is_zero())
1742     {
1743     ($x1, $xr) = bdiv($x1,$x10000);
1744     ($y1, $yr) = bdiv($y1,$x10000);
1745     # make both op's numbers!
1746     $x->badd( bmul( $class->new(
1747        abs($sx*int($xr->numify()) | $sy*int($yr->numify()))), 
1748       $m));
1749     $m->bmul($x10000);
1750     }
1751   $x->bneg() if $sign;
1752   return $x->round($a,$p,$r);
1753   }
1754
1755 sub bxor 
1756   {
1757   #(BINT or num_str, BINT or num_str) return BINT
1758   # compute x ^ y
1759   my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1760
1761   return $x if $x->modify('bxor');
1762
1763   local $Math::BigInt::upgrade = undef;
1764
1765   return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1766   return $x if $y->is_zero();
1767   
1768   my $sign = 0;                                 # sign of result
1769   $sign = 1 if $x->{sign} ne $y->{sign};
1770   my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1771   my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1772
1773   # don't use lib for negative values
1774   if ($CALC->can('_xor') && $sx == 1 && $sy == 1)
1775     {
1776     $x->{value} = $CALC->_xor($x->{value},$y->{value});
1777     return $x->round($a,$p,$r);
1778     }
1779
1780   my $m = $self->bone(); my ($xr,$yr);
1781   my $x10000 = $self->new(0x10000);
1782   my $y1 = copy(ref($x),$y);                    # make copy
1783   $y1->babs();                                  # and positive
1784   my $x1 = $x->copy()->babs(); $x->bzero();     # modify x in place!
1785   use integer;                                  # need this for negative bools
1786   while (!$x1->is_zero() || !$y1->is_zero())
1787     {
1788     ($x1, $xr) = bdiv($x1, $x10000);
1789     ($y1, $yr) = bdiv($y1, $x10000);
1790     # make both op's numbers!
1791     $x->badd( bmul( $class->new(
1792        abs($sx*int($xr->numify()) ^ $sy*int($yr->numify()))), 
1793       $m));
1794     $m->bmul($x10000);
1795     }
1796   $x->bneg() if $sign;
1797   return $x->round($a,$p,$r);
1798   }
1799
1800 sub length
1801   {
1802   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1803
1804   my $e = $CALC->_len($x->{value}); 
1805   return wantarray ? ($e,0) : $e;
1806   }
1807
1808 sub digit
1809   {
1810   # return the nth decimal digit, negative values count backward, 0 is right
1811   my ($self,$x,$n) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1812   $n = 0 if !defined $n;
1813
1814   $CALC->_digit($x->{value},$n);
1815   }
1816
1817 sub _trailing_zeros
1818   {
1819   # return the amount of trailing zeros in $x
1820   my $x = shift;
1821   $x = $class->new($x) unless ref $x;
1822
1823   return 0 if $x->is_zero() || $x->is_odd() || $x->{sign} !~ /^[+-]$/;
1824
1825   return $CALC->_zeros($x->{value}) if $CALC->can('_zeros');
1826
1827   # if not: since we do not know underlying internal representation:
1828   my $es = "$x"; $es =~ /([0]*)$/;
1829   return 0 if !defined $1;      # no zeros
1830   return CORE::length("$1");    # as string, not as +0!
1831   }
1832
1833 sub bsqrt
1834   {
1835   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1836
1837   return $x if $x->modify('bsqrt');
1838
1839   return $x->bnan() if $x->{sign} ne '+';       # -x or inf or NaN => NaN
1840   return $x->bzero($a,$p) if $x->is_zero();                     # 0 => 0
1841   return $x->round($a,$p,$r) if $x->is_one();                   # 1 => 1
1842
1843   return $upgrade->bsqrt($x,$a,$p,$r) if defined $upgrade;
1844
1845   if ($CALC->can('_sqrt'))
1846     {
1847     $x->{value} = $CALC->_sqrt($x->{value});
1848     return $x->round($a,$p,$r);
1849     }
1850
1851   return $x->bone($a,$p) if $x < 4;                             # 2,3 => 1
1852   my $y = $x->copy();
1853   my $l = int($x->length()/2);
1854   
1855   $x->bone();                                   # keep ref($x), but modify it
1856   $x->blsft($l,10);
1857
1858   my $last = $self->bzero();
1859   my $two = $self->new(2);
1860   my $lastlast = $x+$two;
1861   while ($last != $x && $lastlast != $x)
1862     {
1863     $lastlast = $last; $last = $x; 
1864     $x += $y / $x; 
1865     $x /= $two;
1866     }
1867   $x-- if $x * $x > $y;                         # overshot?
1868   $x->round($a,$p,$r);
1869   }
1870
1871 sub exponent
1872   {
1873   # return a copy of the exponent (here always 0, NaN or 1 for $m == 0)
1874   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1875  
1876   if ($x->{sign} !~ /^[+-]$/)
1877     {
1878     my $s = $x->{sign}; $s =~ s/^[+-]//;
1879     return $self->new($s);              # -inf,+inf => inf
1880     }
1881   my $e = $class->bzero();
1882   return $e->binc() if $x->is_zero();
1883   $e += $x->_trailing_zeros();
1884   $e;
1885   }
1886
1887 sub mantissa
1888   {
1889   # return the mantissa (compatible to Math::BigFloat, e.g. reduced)
1890   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1891
1892   if ($x->{sign} !~ /^[+-]$/)
1893     {
1894     return $self->new($x->{sign});              # keep + or - sign
1895     }
1896   my $m = $x->copy();
1897   # that's inefficient
1898   my $zeros = $m->_trailing_zeros();
1899   $m->brsft($zeros,10) if $zeros != 0;
1900 #  $m /= 10 ** $zeros if $zeros != 0;
1901   $m;
1902   }
1903
1904 sub parts
1905   {
1906   # return a copy of both the exponent and the mantissa
1907   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1908
1909   return ($x->mantissa(),$x->exponent());
1910   }
1911    
1912 ##############################################################################
1913 # rounding functions
1914
1915 sub bfround
1916   {
1917   # precision: round to the $Nth digit left (+$n) or right (-$n) from the '.'
1918   # $n == 0 || $n == 1 => round to integer
1919   my $x = shift; $x = $class->new($x) unless ref $x;
1920   my ($scale,$mode) = $x->_scale_p($x->precision(),$x->round_mode(),@_);
1921   return $x if !defined $scale;         # no-op
1922   return $x if $x->modify('bfround');
1923
1924   # no-op for BigInts if $n <= 0
1925   if ($scale <= 0)
1926     {
1927     $x->{_a} = undef;                           # clear an eventual set A
1928     $x->{_p} = $scale; return $x;
1929     }
1930
1931   $x->bround( $x->length()-$scale, $mode);
1932   $x->{_a} = undef;                             # bround sets {_a}
1933   $x->{_p} = $scale;                            # so correct it
1934   $x;
1935   }
1936
1937 sub _scan_for_nonzero
1938   {
1939   my $x = shift;
1940   my $pad = shift;
1941   my $xs = shift;
1942  
1943   my $len = $x->length();
1944   return 0 if $len == 1;                # '5' is trailed by invisible zeros
1945   my $follow = $pad - 1;
1946   return 0 if $follow > $len || $follow < 1;
1947
1948   # since we do not know underlying represention of $x, use decimal string
1949   #my $r = substr ($$xs,-$follow);
1950   my $r = substr ("$x",-$follow);
1951   return 1 if $r =~ /[^0]/; return 0;
1952   }
1953
1954 sub fround
1955   {
1956   # to make life easier for switch between MBF and MBI (autoload fxxx()
1957   # like MBF does for bxxx()?)
1958   my $x = shift;
1959   return $x->bround(@_);
1960   }
1961
1962 sub bround
1963   {
1964   # accuracy: +$n preserve $n digits from left,
1965   #           -$n preserve $n digits from right (f.i. for 0.1234 style in MBF)
1966   # no-op for $n == 0
1967   # and overwrite the rest with 0's, return normalized number
1968   # do not return $x->bnorm(), but $x
1969
1970   my $x = shift; $x = $class->new($x) unless ref $x;
1971   my ($scale,$mode) = $x->_scale_a($x->accuracy(),$x->round_mode(),@_);
1972   return $x if !defined $scale;                 # no-op
1973   return $x if $x->modify('bround');
1974   
1975   if ($x->is_zero() || $scale == 0)
1976     {
1977     $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
1978     return $x;
1979     }
1980   return $x if $x->{sign} !~ /^[+-]$/;          # inf, NaN
1981
1982   # we have fewer digits than we want to scale to
1983   my $len = $x->length();
1984   # scale < 0, but > -len (not >=!)
1985   if (($scale < 0 && $scale < -$len-1) || ($scale >= $len))
1986     {
1987     $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
1988     return $x; 
1989     }
1990    
1991   # count of 0's to pad, from left (+) or right (-): 9 - +6 => 3, or |-6| => 6
1992   my ($pad,$digit_round,$digit_after);
1993   $pad = $len - $scale;
1994   $pad = abs($scale-1) if $scale < 0;
1995
1996   # do not use digit(), it is costly for binary => decimal
1997
1998   my $xs = $CALC->_str($x->{value});
1999   my $pl = -$pad-1;
2000  
2001   # pad:   123: 0 => -1, at 1 => -2, at 2 => -3, at 3 => -4
2002   # pad+1: 123: 0 => 0,  at 1 => -1, at 2 => -2, at 3 => -3
2003   $digit_round = '0'; $digit_round = substr($$xs,$pl,1) if $pad <= $len;
2004   $pl++; $pl ++ if $pad >= $len;
2005   $digit_after = '0'; $digit_after = substr($$xs,$pl,1) if $pad > 0;
2006
2007  #  print "$pad $pl $$xs dr $digit_round da $digit_after\n";
2008
2009   # in case of 01234 we round down, for 6789 up, and only in case 5 we look
2010   # closer at the remaining digits of the original $x, remember decision
2011   my $round_up = 1;                                     # default round up
2012   $round_up -- if
2013     ($mode eq 'trunc')                          ||      # trunc by round down
2014     ($digit_after =~ /[01234]/)                 ||      # round down anyway,
2015                                                         # 6789 => round up
2016     ($digit_after eq '5')                       &&      # not 5000...0000
2017     ($x->_scan_for_nonzero($pad,$xs) == 0)              &&
2018     (
2019      ($mode eq 'even') && ($digit_round =~ /[24680]/) ||
2020      ($mode eq 'odd')  && ($digit_round =~ /[13579]/) ||
2021      ($mode eq '+inf') && ($x->{sign} eq '-')   ||
2022      ($mode eq '-inf') && ($x->{sign} eq '+')   ||
2023      ($mode eq 'zero')          # round down if zero, sign adjusted below
2024     );
2025   my $put_back = 0;                                     # not yet modified
2026         
2027   # old code, depend on internal representation
2028   # split mantissa at $pad and then pad with zeros
2029   #my $s5 = int($pad / 5);
2030   #my $i = 0;
2031   #while ($i < $s5)
2032   #  {
2033   #  $x->{value}->[$i++] = 0;                           # replace with 5 x 0
2034   #  }
2035   #$x->{value}->[$s5] = '00000'.$x->{value}->[$s5];     # pad with 0
2036   #my $rem = $pad % 5;                          # so much left over
2037   #if ($rem > 0)
2038   #  {
2039   #  #print "remainder $rem\n";
2040   ##  #print "elem      $x->{value}->[$s5]\n";
2041   #  substr($x->{value}->[$s5],-$rem,$rem) = '0' x $rem;        # stamp w/ '0'
2042   #  }
2043   #$x->{value}->[$s5] = int ($x->{value}->[$s5]);       # str '05' => int '5'
2044   #print ${$CALC->_str($pad->{value})}," $len\n";
2045
2046   if (($pad > 0) && ($pad <= $len))
2047     {
2048     substr($$xs,-$pad,$pad) = '0' x $pad;
2049     $put_back = 1;
2050     }
2051   elsif ($pad > $len)
2052     {
2053     $x->bzero();                                        # round to '0'
2054     }
2055
2056   if ($round_up)                                        # what gave test above?
2057     {
2058     $put_back = 1;
2059     $pad = $len, $$xs = '0'x$pad if $scale < 0;         # tlr: whack 0.51=>1.0  
2060
2061     # we modify directly the string variant instead of creating a number and
2062     # adding it
2063     my $c = 0; $pad ++;                         # for $pad == $len case
2064     while ($pad <= $len)
2065       {
2066       $c = substr($$xs,-$pad,1) + 1; $c = '0' if $c eq '10';
2067       substr($$xs,-$pad,1) = $c; $pad++;
2068       last if $c != 0;                          # no overflow => early out
2069       }
2070     $$xs = '1'.$$xs if $c == 0;
2071
2072     # $x->badd( Math::BigInt->new($x->{sign}.'1'. '0' x $pad) );
2073     }
2074   $x->{value} = $CALC->_new($xs) if $put_back == 1;     # put back in
2075
2076   $x->{_a} = $scale if $scale >= 0;
2077   if ($scale < 0)
2078     {
2079     $x->{_a} = $len+$scale;
2080     $x->{_a} = 0 if $scale < -$len;
2081     }
2082   $x;
2083   }
2084
2085 sub bfloor
2086   {
2087   # return integer less or equal then number, since it is already integer,
2088   # always returns $self
2089   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
2090
2091   # not needed: return $x if $x->modify('bfloor');
2092   return $x->round($a,$p,$r);
2093   }
2094
2095 sub bceil
2096   {
2097   # return integer greater or equal then number, since it is already integer,
2098   # always returns $self
2099   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
2100
2101   # not needed: return $x if $x->modify('bceil');
2102   return $x->round($a,$p,$r);
2103   }
2104
2105 ##############################################################################
2106 # private stuff (internal use only)
2107
2108 sub __one
2109   {
2110   # internal speedup, set argument to 1, or create a +/- 1
2111   my $self = shift;
2112   my $x = $self->bone(); # $x->{value} = $CALC->_one();
2113   $x->{sign} = shift || '+';
2114   return $x;
2115   }
2116
2117 sub _swap
2118   {
2119   # Overload will swap params if first one is no object ref so that the first
2120   # one is always an object ref. In this case, third param is true.
2121   # This routine is to overcome the effect of scalar,$object creating an object
2122   # of the class of this package, instead of the second param $object. This
2123   # happens inside overload, when the overload section of this package is
2124   # inherited by sub classes.
2125   # For overload cases (and this is used only there), we need to preserve the
2126   # args, hence the copy().
2127   # You can override this method in a subclass, the overload section will call
2128   # $object->_swap() to make sure it arrives at the proper subclass, with some
2129   # exceptions like '+' and '-'. To make '+' and '-' work, you also need to
2130   # specify your own overload for them.
2131
2132   # object, (object|scalar) => preserve first and make copy
2133   # scalar, object          => swapped, re-swap and create new from first
2134   #                            (using class of second object, not $class!!)
2135   my $self = shift;                     # for override in subclass
2136   if ($_[2])
2137     {
2138     my $c = ref ($_[0]) || $class;      # fallback $class should not happen
2139     return ( $c->new($_[1]), $_[0] );
2140     }
2141   return ( $_[0]->copy(), $_[1] );
2142   }
2143
2144 sub objectify
2145   {
2146   # check for strings, if yes, return objects instead
2147  
2148   # the first argument is number of args objectify() should look at it will
2149   # return $count+1 elements, the first will be a classname. This is because
2150   # overloaded '""' calls bstr($object,undef,undef) and this would result in
2151   # useless objects beeing created and thrown away. So we cannot simple loop
2152   # over @_. If the given count is 0, all arguments will be used.
2153  
2154   # If the second arg is a ref, use it as class.
2155   # If not, try to use it as classname, unless undef, then use $class 
2156   # (aka Math::BigInt). The latter shouldn't happen,though.
2157
2158   # caller:                        gives us:
2159   # $x->badd(1);                => ref x, scalar y
2160   # Class->badd(1,2);           => classname x (scalar), scalar x, scalar y
2161   # Class->badd( Class->(1),2); => classname x (scalar), ref x, scalar y
2162   # Math::BigInt::badd(1,2);    => scalar x, scalar y
2163   # In the last case we check number of arguments to turn it silently into
2164   # $class,1,2. (We can not take '1' as class ;o)
2165   # badd($class,1) is not supported (it should, eventually, try to add undef)
2166   # currently it tries 'Math::BigInt' + 1, which will not work.
2167
2168   # some shortcut for the common cases
2169   # $x->unary_op();
2170   return (ref($_[1]),$_[1]) if (@_ == 2) && ($_[0]||0 == 1) && ref($_[1]);
2171
2172   my $count = abs(shift || 0);
2173   
2174   my (@a,$k,$d);                # resulting array, temp, and downgrade 
2175   if (ref $_[0])
2176     {
2177     # okay, got object as first
2178     $a[0] = ref $_[0];
2179     }
2180   else
2181     {
2182     # nope, got 1,2 (Class->xxx(1) => Class,1 and not supported)
2183     $a[0] = $class;
2184     $a[0] = shift if $_[0] =~ /^[A-Z].*::/;     # classname as first?
2185     }
2186
2187   no strict 'refs';
2188   # disable downgrading, because Math::BigFLoat->foo('1.0','2.0') needs floats
2189   if (defined ${"$a[0]::downgrade"})
2190     {
2191     $d = ${"$a[0]::downgrade"};
2192     ${"$a[0]::downgrade"} = undef;
2193     }
2194
2195   my $up = ${"$a[0]::upgrade"};
2196   # print "Now in objectify, my class is today $a[0]\n";
2197   if ($count == 0)
2198     {
2199     while (@_)
2200       {
2201       $k = shift;
2202       if (!ref($k))
2203         {
2204         $k = $a[0]->new($k);
2205         }
2206       elsif (!defined $up && ref($k) ne $a[0])
2207         {
2208         # foreign object, try to convert to integer
2209         $k->can('as_number') ?  $k = $k->as_number() : $k = $a[0]->new($k);
2210         }
2211       push @a,$k;
2212       }
2213     }
2214   else
2215     {
2216     while ($count > 0)
2217       {
2218       $count--; 
2219       $k = shift; 
2220       if (!ref($k))
2221         {
2222         $k = $a[0]->new($k);
2223         }
2224       elsif (!defined $up && ref($k) ne $a[0])
2225         {
2226         # foreign object, try to convert to integer
2227         $k->can('as_number') ?  $k = $k->as_number() : $k = $a[0]->new($k);
2228         }
2229       push @a,$k;
2230       }
2231     push @a,@_;         # return other params, too
2232     }
2233   die "$class objectify needs list context" unless wantarray;
2234   ${"$a[0]::downgrade"} = $d;
2235   @a;
2236   }
2237
2238 sub import 
2239   {
2240   my $self = shift;
2241
2242   $IMPORT++;
2243   my @a; my $l = scalar @_;
2244   for ( my $i = 0; $i < $l ; $i++ )
2245     {
2246     if ($_[$i] eq ':constant')
2247       {
2248       # this causes overlord er load to step in
2249       overload::constant integer => sub { $self->new(shift) };
2250       overload::constant binary => sub { $self->new(shift) };
2251       }
2252     elsif ($_[$i] eq 'upgrade')
2253       {
2254       # this causes upgrading
2255       $upgrade = $_[$i+1];              # or undef to disable
2256       $i++;
2257       }
2258     elsif ($_[$i] =~ /^lib$/i)
2259       {
2260       # this causes a different low lib to take care...
2261       $CALC = $_[$i+1] || '';
2262       $i++;
2263       }
2264     else
2265       {
2266       push @a, $_[$i];
2267       }
2268     }
2269   # any non :constant stuff is handled by our parent, Exporter
2270   # even if @_ is empty, to give it a chance 
2271   $self->SUPER::import(@a);                     # need it for subclasses
2272   $self->export_to_level(1,$self,@a);           # need it for MBF
2273
2274   # try to load core math lib
2275   my @c = split /\s*,\s*/,$CALC;
2276   push @c,'Calc';                               # if all fail, try this
2277   $CALC = '';                                   # signal error
2278   foreach my $lib (@c)
2279     {
2280     $lib = 'Math::BigInt::'.$lib if $lib !~ /^Math::BigInt/i;
2281     $lib =~ s/\.pm$//;
2282     if ($] < 5.006)
2283       {
2284       # Perl < 5.6.0 dies with "out of memory!" when eval() and ':constant' is
2285       # used in the same script, or eval inside import().
2286       (my $mod = $lib . '.pm') =~ s!::!/!g;
2287       # require does not automatically :: => /, so portability problems arise
2288       eval { require $mod; $lib->import( @c ); }
2289       }
2290     else
2291       {
2292       eval "use $lib qw/@c/;";
2293       }
2294     $CALC = $lib, last if $@ eq '';     # no error in loading lib?
2295     }
2296   die "Couldn't load any math lib, not even the default" if $CALC eq '';
2297   }
2298
2299 sub __from_hex
2300   {
2301   # convert a (ref to) big hex string to BigInt, return undef for error
2302   my $hs = shift;
2303
2304   my $x = Math::BigInt->bzero();
2305   
2306   # strip underscores
2307   $$hs =~ s/([0-9a-fA-F])_([0-9a-fA-F])/$1$2/g; 
2308   $$hs =~ s/([0-9a-fA-F])_([0-9a-fA-F])/$1$2/g; 
2309   
2310   return $x->bnan() if $$hs !~ /^[\-\+]?0x[0-9A-Fa-f]+$/;
2311
2312   my $sign = '+'; $sign = '-' if ($$hs =~ /^-/);
2313
2314   $$hs =~ s/^[+-]//;                    # strip sign
2315   if ($CALC->can('_from_hex'))
2316     {
2317     $x->{value} = $CALC->_from_hex($hs);
2318     }
2319   else
2320     {
2321     # fallback to pure perl
2322     my $mul = Math::BigInt->bzero(); $mul++;
2323     my $x65536 = Math::BigInt->new(65536);
2324     my $len = CORE::length($$hs)-2;
2325     $len = int($len/4);                 # 4-digit parts, w/o '0x'
2326     my $val; my $i = -4;
2327     while ($len >= 0)
2328       {
2329       $val = substr($$hs,$i,4);
2330       $val =~ s/^[+-]?0x// if $len == 0;        # for last part only because
2331       $val = hex($val);                         # hex does not like wrong chars
2332       $i -= 4; $len --;
2333       $x += $mul * $val if $val != 0;
2334       $mul *= $x65536 if $len >= 0;             # skip last mul
2335       }
2336     }
2337   $x->{sign} = $sign unless $CALC->_is_zero($x->{value});       # no '-0'
2338   $x;
2339   }
2340
2341 sub __from_bin
2342   {
2343   # convert a (ref to) big binary string to BigInt, return undef for error
2344   my $bs = shift;
2345
2346   my $x = Math::BigInt->bzero();
2347   # strip underscores
2348   $$bs =~ s/([01])_([01])/$1$2/g;       
2349   $$bs =~ s/([01])_([01])/$1$2/g;       
2350   return $x->bnan() if $$bs !~ /^[+-]?0b[01]+$/;
2351
2352   my $sign = '+'; $sign = '-' if ($$bs =~ /^\-/);
2353   $$bs =~ s/^[+-]//;                            # strip sign
2354   if ($CALC->can('_from_bin'))
2355     {
2356     $x->{value} = $CALC->_from_bin($bs);
2357     }
2358   else
2359     {
2360     my $mul = Math::BigInt->bzero(); $mul++;
2361     my $x256 = Math::BigInt->new(256);
2362     my $len = CORE::length($$bs)-2;
2363     $len = int($len/8);                         # 8-digit parts, w/o '0b'
2364     my $val; my $i = -8;
2365     while ($len >= 0)
2366       {
2367       $val = substr($$bs,$i,8);
2368       $val =~ s/^[+-]?0b// if $len == 0;        # for last part only
2369       #$val = oct('0b'.$val);   # does not work on Perl prior to 5.6.0
2370       # slower:
2371       # $val = ('0' x (8-CORE::length($val))).$val if CORE::length($val) < 8;
2372       $val = ord(pack('B8',substr('00000000'.$val,-8,8)));
2373       $i -= 8; $len --;
2374       $x += $mul * $val if $val != 0;
2375       $mul *= $x256 if $len >= 0;               # skip last mul
2376       }
2377     }
2378   $x->{sign} = $sign unless $CALC->_is_zero($x->{value});       # no '-0'
2379   $x;
2380   }
2381
2382 sub _split
2383   {
2384   # (ref to num_str) return num_str
2385   # internal, take apart a string and return the pieces
2386   # strip leading/trailing whitespace, leading zeros, underscore and reject
2387   # invalid input
2388   my $x = shift;
2389
2390   # strip white space at front, also extranous leading zeros
2391   $$x =~ s/^\s*([-]?)0*([0-9])/$1$2/g;  # will not strip '  .2'
2392   $$x =~ s/^\s+//;                      # but this will                 
2393   $$x =~ s/\s+$//g;                     # strip white space at end
2394
2395   # shortcut, if nothing to split, return early
2396   if ($$x =~ /^[+-]?\d+$/)
2397     {
2398     $$x =~ s/^([+-])0*([0-9])/$2/; my $sign = $1 || '+';
2399     return (\$sign, $x, \'', \'', \0);
2400     }
2401
2402   # invalid starting char?
2403   return if $$x !~ /^[+-]?(\.?[0-9]|0b[0-1]|0x[0-9a-fA-F])/;
2404
2405   return __from_hex($x) if $$x =~ /^[\-\+]?0x/; # hex string
2406   return __from_bin($x) if $$x =~ /^[\-\+]?0b/; # binary string
2407   
2408   # strip underscores between digits
2409   $$x =~ s/(\d)_(\d)/$1$2/g;
2410   $$x =~ s/(\d)_(\d)/$1$2/g;            # do twice for 1_2_3
2411
2412   # some possible inputs: 
2413   # 2.1234 # 0.12        # 1          # 1E1 # 2.134E1 # 434E-10 # 1.02009E-2 
2414   # .2     # 1_2_3.4_5_6 # 1.4E1_2_3  # 1e3 # +.2
2415
2416   return if $$x =~ /[Ee].*[Ee]/;        # more than one E => error
2417
2418   my ($m,$e) = split /[Ee]/,$$x;
2419   $e = '0' if !defined $e || $e eq "";
2420   # sign,value for exponent,mantint,mantfrac
2421   my ($es,$ev,$mis,$miv,$mfv);
2422   # valid exponent?
2423   if ($e =~ /^([+-]?)0*(\d+)$/) # strip leading zeros
2424     {
2425     $es = $1; $ev = $2;
2426     # valid mantissa?
2427     return if $m eq '.' || $m eq '';
2428     my ($mi,$mf) = split /\./,$m;
2429     $mi = '0' if !defined $mi;
2430     $mi .= '0' if $mi =~ /^[\-\+]?$/;
2431     $mf = '0' if !defined $mf || $mf eq '';
2432     if ($mi =~ /^([+-]?)0*(\d+)$/) # strip leading zeros
2433       {
2434       $mis = $1||'+'; $miv = $2;
2435       return unless ($mf =~ /^(\d*?)0*$/);      # strip trailing zeros
2436       $mfv = $1;
2437       return (\$mis,\$miv,\$mfv,\$es,\$ev);
2438       }
2439     }
2440   return; # NaN, not a number
2441   }
2442
2443 sub as_number
2444   {
2445   # an object might be asked to return itself as bigint on certain overloaded
2446   # operations, this does exactly this, so that sub classes can simple inherit
2447   # it or override with their own integer conversion routine
2448   my $self = shift;
2449
2450   $self->copy();
2451   }
2452
2453 sub as_hex
2454   {
2455   # return as hex string, with prefixed 0x
2456   my $x = shift; $x = $class->new($x) if !ref($x);
2457
2458   return $x->bstr() if $x->{sign} !~ /^[+-]$/;  # inf, nan etc
2459   return '0x0' if $x->is_zero();
2460
2461   my $es = ''; my $s = '';
2462   $s = $x->{sign} if $x->{sign} eq '-';
2463   if ($CALC->can('_as_hex'))
2464     {
2465     $es = ${$CALC->_as_hex($x->{value})};
2466     }
2467   else
2468     {
2469     my $x1 = $x->copy()->babs(); my $xr;
2470     my $x10000 = Math::BigInt->new (0x10000);
2471     while (!$x1->is_zero())
2472       {
2473       ($x1, $xr) = bdiv($x1,$x10000);
2474       $es .= unpack('h4',pack('v',$xr->numify()));
2475       }
2476     $es = reverse $es;
2477     $es =~ s/^[0]+//;   # strip leading zeros
2478     $s .= '0x';
2479     }
2480   $s . $es;
2481   }
2482
2483 sub as_bin
2484   {
2485   # return as binary string, with prefixed 0b
2486   my $x = shift; $x = $class->new($x) if !ref($x);
2487
2488   return $x->bstr() if $x->{sign} !~ /^[+-]$/;  # inf, nan etc
2489   return '0b0' if $x->is_zero();
2490
2491   my $es = ''; my $s = '';
2492   $s = $x->{sign} if $x->{sign} eq '-';
2493   if ($CALC->can('_as_bin'))
2494     {
2495     $es = ${$CALC->_as_bin($x->{value})};
2496     }
2497   else
2498     {
2499     my $x1 = $x->copy()->babs(); my $xr;
2500     my $x10000 = Math::BigInt->new (0x10000);
2501     while (!$x1->is_zero())
2502       {
2503       ($x1, $xr) = bdiv($x1,$x10000);
2504       $es .= unpack('b16',pack('v',$xr->numify()));
2505       }
2506     $es = reverse $es; 
2507     $es =~ s/^[0]+//;   # strip leading zeros
2508     $s .= '0b';
2509     }
2510   $s . $es;
2511   }
2512
2513 ##############################################################################
2514 # internal calculation routines (others are in Math::BigInt::Calc etc)
2515
2516 sub __lcm 
2517   { 
2518   # (BINT or num_str, BINT or num_str) return BINT
2519   # does modify first argument
2520   # LCM
2521  
2522   my $x = shift; my $ty = shift;
2523   return $x->bnan() if ($x->{sign} eq $nan) || ($ty->{sign} eq $nan);
2524   return $x * $ty / bgcd($x,$ty);
2525   }
2526
2527 sub __gcd
2528   { 
2529   # (BINT or num_str, BINT or num_str) return BINT
2530   # does modify both arguments
2531   # GCD -- Euclids algorithm E, Knuth Vol 2 pg 296
2532   my ($x,$ty) = @_;
2533
2534   return $x->bnan() if $x->{sign} !~ /^[+-]$/ || $ty->{sign} !~ /^[+-]$/;
2535
2536   while (!$ty->is_zero())
2537     {
2538     ($x, $ty) = ($ty,bmod($x,$ty));
2539     }
2540   $x;
2541   }
2542
2543 ###############################################################################
2544 # this method return 0 if the object can be modified, or 1 for not
2545 # We use a fast use constant statement here, to avoid costly calls. Subclasses
2546 # may override it with special code (f.i. Math::BigInt::Constant does so)
2547
2548 sub modify () { 0; }
2549
2550 1;
2551 __END__
2552
2553 =head1 NAME
2554
2555 Math::BigInt - Arbitrary size integer math package
2556
2557 =head1 SYNOPSIS
2558
2559   use Math::BigInt;
2560
2561   # Number creation     
2562   $x = Math::BigInt->new($str);         # defaults to 0
2563   $nan  = Math::BigInt->bnan();         # create a NotANumber
2564   $zero = Math::BigInt->bzero();        # create a +0
2565   $inf = Math::BigInt->binf();          # create a +inf
2566   $inf = Math::BigInt->binf('-');       # create a -inf
2567   $one = Math::BigInt->bone();          # create a +1
2568   $one = Math::BigInt->bone('-');       # create a -1
2569
2570   # Testing
2571   $x->is_zero();                # true if arg is +0
2572   $x->is_nan();                 # true if arg is NaN
2573   $x->is_one();                 # true if arg is +1
2574   $x->is_one('-');              # true if arg is -1
2575   $x->is_odd();                 # true if odd, false for even
2576   $x->is_even();                # true if even, false for odd
2577   $x->is_positive();            # true if >= 0
2578   $x->is_negative();            # true if <  0
2579   $x->is_inf(sign);             # true if +inf, or -inf (sign is default '+')
2580   $x->is_int();                 # true if $x is an integer (not a float)
2581
2582   $x->bcmp($y);                 # compare numbers (undef,<0,=0,>0)
2583   $x->bacmp($y);                # compare absolutely (undef,<0,=0,>0)
2584   $x->sign();                   # return the sign, either +,- or NaN
2585   $x->digit($n);                # return the nth digit, counting from right
2586   $x->digit(-$n);               # return the nth digit, counting from left
2587
2588   # The following all modify their first argument:
2589
2590   # set 
2591   $x->bzero();                  # set $x to 0
2592   $x->bnan();                   # set $x to NaN
2593   $x->bone();                   # set $x to +1
2594   $x->bone('-');                # set $x to -1
2595   $x->binf();                   # set $x to inf
2596   $x->binf('-');                # set $x to -inf
2597
2598   $x->bneg();                   # negation
2599   $x->babs();                   # absolute value
2600   $x->bnorm();                  # normalize (no-op)
2601   $x->bnot();                   # two's complement (bit wise not)
2602   $x->binc();                   # increment x by 1
2603   $x->bdec();                   # decrement x by 1
2604   
2605   $x->badd($y);                 # addition (add $y to $x)
2606   $x->bsub($y);                 # subtraction (subtract $y from $x)
2607   $x->bmul($y);                 # multiplication (multiply $x by $y)
2608   $x->bdiv($y);                 # divide, set $x to quotient
2609                                 # return (quo,rem) or quo if scalar
2610
2611   $x->bmod($y);                 # modulus (x % y)
2612
2613   $x->bpow($y);                 # power of arguments (x ** y)
2614   $x->blsft($y);                # left shift
2615   $x->brsft($y);                # right shift 
2616   $x->blsft($y,$n);             # left shift, by base $n (like 10)
2617   $x->brsft($y,$n);             # right shift, by base $n (like 10)
2618   
2619   $x->band($y);                 # bitwise and
2620   $x->bior($y);                 # bitwise inclusive or
2621   $x->bxor($y);                 # bitwise exclusive or
2622   $x->bnot();                   # bitwise not (two's complement)
2623
2624   $x->bsqrt();                  # calculate square-root
2625   $x->bfac();                   # factorial of $x (1*2*3*4*..$x)
2626
2627   $x->round($A,$P,$round_mode); # round to accuracy or precision using mode $r
2628   $x->bround($N);               # accuracy: preserve $N digits
2629   $x->bfround($N);              # round to $Nth digit, no-op for BigInts
2630
2631   # The following do not modify their arguments in BigInt, but do in BigFloat:
2632   $x->bfloor();                 # return integer less or equal than $x
2633   $x->bceil();                  # return integer greater or equal than $x
2634   
2635   # The following do not modify their arguments:
2636
2637   bgcd(@values);                # greatest common divisor (no OO style)
2638   blcm(@values);                # lowest common multiplicator (no OO style)
2639  
2640   $x->length();                 # return number of digits in number
2641   ($x,$f) = $x->length();       # length of number and length of fraction part,
2642                                 # latter is always 0 digits long for BigInt's
2643
2644   $x->exponent();               # return exponent as BigInt
2645   $x->mantissa();               # return (signed) mantissa as BigInt
2646   $x->parts();                  # return (mantissa,exponent) as BigInt
2647   $x->copy();                   # make a true copy of $x (unlike $y = $x;)
2648   $x->as_number();              # return as BigInt (in BigInt: same as copy())
2649   
2650   # conversation to string 
2651   $x->bstr();                   # normalized string
2652   $x->bsstr();                  # normalized string in scientific notation
2653   $x->as_hex();                 # as signed hexadecimal string with prefixed 0x
2654   $x->as_bin();                 # as signed binary string with prefixed 0b
2655   
2656   Math::BigInt->config();       # return hash containing configuration/version
2657
2658 =head1 DESCRIPTION
2659
2660 All operators (inlcuding basic math operations) are overloaded if you
2661 declare your big integers as
2662
2663   $i = new Math::BigInt '123_456_789_123_456_789';
2664
2665 Operations with overloaded operators preserve the arguments which is
2666 exactly what you expect.
2667
2668 =over 2
2669
2670 =item Canonical notation
2671
2672 Big integer values are strings of the form C</^[+-]\d+$/> with leading
2673 zeros suppressed.
2674
2675    '-0'                            canonical value '-0', normalized '0'
2676    '   -123_123_123'               canonical value '-123123123'
2677    '1_23_456_7890'                 canonical value '1234567890'
2678
2679 =item Input
2680
2681 Input values to these routines may be either Math::BigInt objects or
2682 strings of the form C</^\s*[+-]?[\d]+\.?[\d]*E?[+-]?[\d]*$/>.
2683
2684 You can include one underscore between any two digits.
2685
2686 This means integer values like 1.01E2 or even 1000E-2 are also accepted.
2687 Non integer values result in NaN.
2688
2689 Math::BigInt::new() defaults to 0, while Math::BigInt::new('') results
2690 in 'NaN'.
2691
2692 bnorm() on a BigInt object is now effectively a no-op, since the numbers 
2693 are always stored in normalized form. On a string, it creates a BigInt 
2694 object.
2695
2696 =item Output
2697
2698 Output values are BigInt objects (normalized), except for bstr(), which
2699 returns a string in normalized form.
2700 Some routines (C<is_odd()>, C<is_even()>, C<is_zero()>, C<is_one()>,
2701 C<is_nan()>) return true or false, while others (C<bcmp()>, C<bacmp()>)
2702 return either undef, <0, 0 or >0 and are suited for sort.
2703
2704 =back
2705
2706 =head1 METHODS
2707
2708 Each of the methods below accepts three additional parameters. These arguments
2709 $A, $P and $R are accuracy, precision and round_mode. Please see more in the
2710 section about ACCURACY and ROUNDIND.
2711
2712 =head2 config
2713
2714         use Data::Dumper;
2715
2716         print Dumper ( Math::BigInt->config() );
2717
2718 Returns a hash containing the configuration, e.g. the version number, lib
2719 loaded etc.
2720
2721 =head2 accuracy
2722
2723         $x->accuracy(5);                # local for $x
2724         $class->accuracy(5);            # global for all members of $class
2725
2726 Set or get the global or local accuracy, aka how many significant digits the
2727 results have. Please see the section about L<ACCURACY AND PRECISION> for
2728 further details.
2729
2730 Value must be greater than zero. Pass an undef value to disable it:
2731
2732         $x->accuracy(undef);
2733         Math::BigInt->accuracy(undef);
2734
2735 Returns the current accuracy. For C<$x->accuracy()> it will return either the
2736 local accuracy, or if not defined, the global. This means the return value
2737 represents the accuracy that will be in effect for $x:
2738
2739         $y = Math::BigInt->new(1234567);        # unrounded
2740         print Math::BigInt->accuracy(4),"\n";   # set 4, print 4
2741         $x = Math::BigInt->new(123456);         # will be automatically rounded
2742         print "$x $y\n";                        # '123500 1234567'
2743         print $x->accuracy(),"\n";              # will be 4
2744         print $y->accuracy(),"\n";              # also 4, since global is 4
2745         print Math::BigInt->accuracy(5),"\n";   # set to 5, print 5
2746         print $x->accuracy(),"\n";              # still 4
2747         print $y->accuracy(),"\n";              # 5, since global is 5
2748
2749 =head2 brsft
2750
2751         $x->brsft($y,$n);               
2752
2753 Shifts $x right by $y in base $n. Default is base 2, used are usually 10 and
2754 2, but others work, too.
2755
2756 Right shifting usually amounts to dividing $x by $n ** $y and truncating the
2757 result:
2758
2759
2760         $x = Math::BigInt->new(10);
2761         $x->brsft(1);                   # same as $x >> 1: 5
2762         $x = Math::BigInt->new(1234);
2763         $x->brsft(2,10);                # result 12
2764
2765 There is one exception, and that is base 2 with negative $x:
2766
2767
2768         $x = Math::BigInt->new(-5);
2769         print $x->brsft(1);
2770
2771 This will print -3, not -2 (as it would if you divide -5 by 2 and truncate the
2772 result).
2773
2774 =head2 new
2775
2776         $x = Math::BigInt->new($str,$A,$P,$R);
2777
2778 Creates a new BigInt object from a string or another BigInt object. The
2779 input is accepted as decimal, hex (with leading '0x') or binary (with leading
2780 '0b').
2781
2782 =head2 bnan
2783
2784         $x = Math::BigInt->bnan();
2785
2786 Creates a new BigInt object representing NaN (Not A Number).
2787 If used on an object, it will set it to NaN:
2788
2789         $x->bnan();
2790
2791 =head2 bzero
2792
2793         $x = Math::BigInt->bzero();
2794
2795 Creates a new BigInt object representing zero.
2796 If used on an object, it will set it to zero:
2797
2798         $x->bzero();
2799
2800 =head2 binf
2801
2802         $x = Math::BigInt->binf($sign);
2803
2804 Creates a new BigInt object representing infinity. The optional argument is
2805 either '-' or '+', indicating whether you want infinity or minus infinity.
2806 If used on an object, it will set it to infinity:
2807
2808         $x->binf();
2809         $x->binf('-');
2810
2811 =head2 bone
2812
2813         $x = Math::BigInt->binf($sign);
2814
2815 Creates a new BigInt object representing one. The optional argument is
2816 either '-' or '+', indicating whether you want one or minus one.
2817 If used on an object, it will set it to one:
2818
2819         $x->bone();             # +1
2820         $x->bone('-');          # -1
2821
2822 =head2 is_one()/is_zero()/is_nan()/is_inf()
2823
2824   
2825         $x->is_zero();                  # true if arg is +0
2826         $x->is_nan();                   # true if arg is NaN
2827         $x->is_one();                   # true if arg is +1
2828         $x->is_one('-');                # true if arg is -1
2829         $x->is_inf();                   # true if +inf
2830         $x->is_inf('-');                # true if -inf (sign is default '+')
2831
2832 These methods all test the BigInt for beeing one specific value and return
2833 true or false depending on the input. These are faster than doing something
2834 like:
2835
2836         if ($x == 0)
2837
2838 =head2 is_positive()/is_negative()
2839         
2840         $x->is_positive();              # true if >= 0
2841         $x->is_negative();              # true if <  0
2842
2843 The methods return true if the argument is positive or negative, respectively.
2844 C<NaN> is neither positive nor negative, while C<+inf> counts as positive, and
2845 C<-inf> is negative. A C<zero> is positive.
2846
2847 These methods are only testing the sign, and not the value.
2848
2849 =head2 is_odd()/is_even()/is_int()
2850
2851         $x->is_odd();                   # true if odd, false for even
2852         $x->is_even();                  # true if even, false for odd
2853         $x->is_int();                   # true if $x is an integer
2854
2855 The return true when the argument satisfies the condition. C<NaN>, C<+inf>,
2856 C<-inf> are not integers and are neither odd nor even.
2857
2858 =head2 bcmp
2859
2860         $x->bcmp($y);
2861
2862 Compares $x with $y and takes the sign into account.
2863 Returns -1, 0, 1 or undef.
2864
2865 =head2 bacmp
2866
2867         $x->bacmp($y);
2868
2869 Compares $x with $y while ignoring their. Returns -1, 0, 1 or undef.
2870
2871 =head2 sign
2872
2873         $x->sign();
2874
2875 Return the sign, of $x, meaning either C<+>, C<->, C<-inf>, C<+inf> or NaN.
2876
2877 =head2 bcmp
2878
2879   $x->digit($n);                # return the nth digit, counting from right
2880
2881 =head2 bneg
2882
2883         $x->bneg();
2884
2885 Negate the number, e.g. change the sign between '+' and '-', or between '+inf'
2886 and '-inf', respectively. Does nothing for NaN or zero.
2887
2888 =head2 babs
2889
2890         $x->babs();
2891
2892 Set the number to it's absolute value, e.g. change the sign from '-' to '+'
2893 and from '-inf' to '+inf', respectively. Does nothing for NaN or positive
2894 numbers.
2895
2896 =head2 bnorm
2897
2898   $x->bnorm();                  # normalize (no-op)
2899
2900 =head2 bnot
2901
2902   $x->bnot();                   # two's complement (bit wise not)
2903
2904 =head2 binc
2905
2906   $x->binc();                   # increment x by 1
2907
2908 =head2 bdec
2909
2910   $x->bdec();                   # decrement x by 1
2911
2912 =head2 badd
2913
2914   $x->badd($y);                 # addition (add $y to $x)
2915
2916 =head2 bsub
2917
2918   $x->bsub($y);                 # subtraction (subtract $y from $x)
2919
2920 =head2 bmul
2921
2922   $x->bmul($y);                 # multiplication (multiply $x by $y)
2923
2924 =head2 bdiv
2925
2926   $x->bdiv($y);                 # divide, set $x to quotient
2927                                 # return (quo,rem) or quo if scalar
2928
2929 =head2 bmod
2930
2931   $x->bmod($y);                 # modulus (x % y)
2932
2933 =head2 bmodinv
2934
2935 Not yet implemented.
2936
2937   bmodinv($num,$mod);          # modular inverse (no OO style)
2938
2939 Returns the inverse of C<$num> in the given modulus C<$mod>.  'C<NaN>' is
2940 returned unless C<$num> is relatively prime to C<$mod>, i.e. unless
2941 C<bgcd($num, $mod)==1>.
2942
2943 =head2 bmodpow
2944
2945 Not yet implemented.
2946
2947   bmodpow($num,$exp,$mod);     # modular exponentation ($num**$exp % $mod)
2948
2949 Returns the value of C<$num> taken to the power C<$exp> in the modulus
2950 C<$mod> using binary exponentation.  C<bmodpow> is far superior to
2951 writing
2952
2953   $num ** $exp % $mod
2954
2955 because C<bmodpow> is much faster--it reduces internal variables into
2956 the modulus whenever possible, so it operates on smaller numbers.
2957
2958 C<bmodpow> also supports negative exponents.
2959
2960   bmodpow($num, -1, $mod)
2961
2962 is exactly equivalent to
2963
2964   bmodinv($num, $mod)
2965
2966 =head2 bpow
2967
2968   $x->bpow($y);                 # power of arguments (x ** y)
2969
2970 =head2 blsft
2971
2972   $x->blsft($y);                # left shift
2973   $x->blsft($y,$n);             # left shift, by base $n (like 10)
2974
2975 =head2 brsft
2976
2977   $x->brsft($y);                # right shift 
2978   $x->brsft($y,$n);             # right shift, by base $n (like 10)
2979
2980 =head2 band
2981
2982   $x->band($y);                 # bitwise and
2983
2984 =head2 bior
2985
2986   $x->bior($y);                 # bitwise inclusive or
2987
2988 =head2 bxor
2989
2990   $x->bxor($y);                 # bitwise exclusive or
2991
2992 =head2 bnot
2993
2994   $x->bnot();                   # bitwise not (two's complement)
2995
2996 =head2 bsqrt
2997
2998   $x->bsqrt();                  # calculate square-root
2999
3000 =head2 bfac
3001
3002   $x->bfac();                   # factorial of $x (1*2*3*4*..$x)
3003
3004 =head2 round
3005
3006   $x->round($A,$P,$round_mode); # round to accuracy or precision using mode $r
3007
3008 =head2 bround
3009
3010   $x->bround($N);               # accuracy: preserve $N digits
3011
3012 =head2 bfround
3013
3014   $x->bfround($N);              # round to $Nth digit, no-op for BigInts
3015
3016 =head2 bfloor
3017
3018         $x->bfloor();                   
3019
3020 Set $x to the integer less or equal than $x. This is a no-op in BigInt, but
3021 does change $x in BigFloat.
3022
3023 =head2 bceil
3024
3025         $x->bceil();
3026
3027 Set $x to the integer greater or equal than $x. This is a no-op in BigInt, but
3028 does change $x in BigFloat.
3029
3030 =head2 bgcd
3031
3032   bgcd(@values);                # greatest common divisor (no OO style)
3033
3034 =head2 blcm
3035
3036   blcm(@values);                # lowest common multiplicator (no OO style)
3037  
3038 head2 length
3039
3040         $x->length();
3041         ($xl,$fl) = $x->length();
3042
3043 Returns the number of digits in the decimal representation of the number.
3044 In list context, returns the length of the integer and fraction part. For
3045 BigInt's, the length of the fraction part will always be 0.
3046
3047 =head2 exponent
3048
3049         $x->exponent();
3050
3051 Return the exponent of $x as BigInt.
3052
3053 =head2 mantissa
3054
3055         $x->mantissa();
3056
3057 Return the signed mantissa of $x as BigInt.
3058
3059 =head2 parts
3060
3061   $x->parts();                  # return (mantissa,exponent) as BigInt
3062
3063 =head2 copy
3064
3065   $x->copy();                   # make a true copy of $x (unlike $y = $x;)
3066
3067 =head2 as_number
3068
3069   $x->as_number();              # return as BigInt (in BigInt: same as copy())
3070   
3071 =head2 bsrt
3072
3073   $x->bstr();                   # normalized string
3074
3075 =head2 bsstr
3076
3077   $x->bsstr();                  # normalized string in scientific notation
3078
3079 =head2 as_hex
3080
3081   $x->as_hex();                 # as signed hexadecimal string with prefixed 0x
3082
3083 =head2 as_bin
3084
3085   $x->as_bin();                 # as signed binary string with prefixed 0b
3086
3087 =head1 ACCURACY and PRECISION
3088
3089 Since version v1.33, Math::BigInt and Math::BigFloat have full support for
3090 accuracy and precision based rounding, both automatically after every
3091 operation as well as manually.
3092
3093 This section describes the accuracy/precision handling in Math::Big* as it
3094 used to be and as it is now, complete with an explanation of all terms and
3095 abbreviations.
3096
3097 Not yet implemented things (but with correct description) are marked with '!',
3098 things that need to be answered are marked with '?'.
3099
3100 In the next paragraph follows a short description of terms used here (because
3101 these may differ from terms used by others people or documentation).
3102
3103 During the rest of this document, the shortcuts A (for accuracy), P (for
3104 precision), F (fallback) and R (rounding mode) will be used.
3105
3106 =head2 Precision P
3107
3108 A fixed number of digits before (positive) or after (negative)
3109 the decimal point. For example, 123.45 has a precision of -2. 0 means an
3110 integer like 123 (or 120). A precision of 2 means two digits to the left
3111 of the decimal point are zero, so 123 with P = 1 becomes 120. Note that
3112 numbers with zeros before the decimal point may have different precisions,
3113 because 1200 can have p = 0, 1 or 2 (depending on what the inital value
3114 was). It could also have p < 0, when the digits after the decimal point
3115 are zero.
3116
3117 The string output (of floating point numbers) will be padded with zeros:
3118  
3119         Initial value   P       A       Result          String
3120         ------------------------------------------------------------
3121         1234.01         -3              1000            1000
3122         1234            -2              1200            1200
3123         1234.5          -1              1230            1230
3124         1234.001        1               1234            1234.0
3125         1234.01         0               1234            1234
3126         1234.01         2               1234.01         1234.01
3127         1234.01         5               1234.01         1234.01000
3128
3129 For BigInts, no padding occurs.
3130
3131 =head2 Accuracy A
3132
3133 Number of significant digits. Leading zeros are not counted. A
3134 number may have an accuracy greater than the non-zero digits
3135 when there are zeros in it or trailing zeros. For example, 123.456 has
3136 A of 6, 10203 has 5, 123.0506 has 7, 123.450000 has 8 and 0.000123 has 3.
3137
3138 The string output (of floating point numbers) will be padded with zeros:
3139
3140         Initial value   P       A       Result          String
3141         ------------------------------------------------------------
3142         1234.01                 3       1230            1230
3143         1234.01                 6       1234.01         1234.01
3144         1234.1                  8       1234.1          1234.1000
3145
3146 For BigInts, no padding occurs.
3147
3148 =head2 Fallback F
3149
3150 When both A and P are undefined, this is used as a fallback accuracy when
3151 dividing numbers.
3152
3153 =head2 Rounding mode R
3154
3155 When rounding a number, different 'styles' or 'kinds'
3156 of rounding are possible. (Note that random rounding, as in
3157 Math::Round, is not implemented.)
3158
3159 =over 2
3160
3161 =item 'trunc'
3162
3163 truncation invariably removes all digits following the
3164 rounding place, replacing them with zeros. Thus, 987.65 rounded
3165 to tens (P=1) becomes 980, and rounded to the fourth sigdig
3166 becomes 987.6 (A=4). 123.456 rounded to the second place after the
3167 decimal point (P=-2) becomes 123.46.
3168
3169 All other implemented styles of rounding attempt to round to the
3170 "nearest digit." If the digit D immediately to the right of the
3171 rounding place (skipping the decimal point) is greater than 5, the
3172 number is incremented at the rounding place (possibly causing a
3173 cascade of incrementation): e.g. when rounding to units, 0.9 rounds
3174 to 1, and -19.9 rounds to -20. If D < 5, the number is similarly
3175 truncated at the rounding place: e.g. when rounding to units, 0.4
3176 rounds to 0, and -19.4 rounds to -19.
3177
3178 However the results of other styles of rounding differ if the
3179 digit immediately to the right of the rounding place (skipping the
3180 decimal point) is 5 and if there are no digits, or no digits other
3181 than 0, after that 5. In such cases:
3182
3183 =item 'even'
3184
3185 rounds the digit at the rounding place to 0, 2, 4, 6, or 8
3186 if it is not already. E.g., when rounding to the first sigdig, 0.45
3187 becomes 0.4, -0.55 becomes -0.6, but 0.4501 becomes 0.5.
3188
3189 =item 'odd'
3190
3191 rounds the digit at the rounding place to 1, 3, 5, 7, or 9 if
3192 it is not already. E.g., when rounding to the first sigdig, 0.45
3193 becomes 0.5, -0.55 becomes -0.5, but 0.5501 becomes 0.6.
3194
3195 =item '+inf'
3196
3197 round to plus infinity, i.e. always round up. E.g., when
3198 rounding to the first sigdig, 0.45 becomes 0.5, -0.55 becomes -0.5,
3199 and 0.4501 also becomes 0.5.
3200
3201 =item '-inf'
3202
3203 round to minus infinity, i.e. always round down. E.g., when
3204 rounding to the first sigdig, 0.45 becomes 0.4, -0.55 becomes -0.6,
3205 but 0.4501 becomes 0.5.
3206
3207 =item 'zero'
3208
3209 round to zero, i.e. positive numbers down, negative ones up.
3210 E.g., when rounding to the first sigdig, 0.45 becomes 0.4, -0.55
3211 becomes -0.5, but 0.4501 becomes 0.5.
3212
3213 =back
3214
3215 The handling of A & P in MBI/MBF (the old core code shipped with Perl
3216 versions <= 5.7.2) is like this:
3217
3218 =over 2
3219
3220 =item Precision
3221
3222   * ffround($p) is able to round to $p number of digits after the decimal
3223     point
3224   * otherwise P is unused
3225
3226 =item Accuracy (significant digits)
3227
3228   * fround($a) rounds to $a significant digits
3229   * only fdiv() and fsqrt() take A as (optional) paramater
3230     + other operations simply create the same number (fneg etc), or more (fmul)
3231       of digits
3232     + rounding/truncating is only done when explicitly calling one of fround
3233       or ffround, and never for BigInt (not implemented)
3234   * fsqrt() simply hands its accuracy argument over to fdiv.
3235   * the documentation and the comment in the code indicate two different ways
3236     on how fdiv() determines the maximum number of digits it should calculate,
3237     and the actual code does yet another thing
3238     POD:
3239       max($Math::BigFloat::div_scale,length(dividend)+length(divisor))
3240     Comment:
3241       result has at most max(scale, length(dividend), length(divisor)) digits
3242     Actual code:
3243       scale = max(scale, length(dividend)-1,length(divisor)-1);
3244       scale += length(divisior) - length(dividend);
3245     So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10+9-3).
3246     Actually, the 'difference' added to the scale is calculated from the
3247     number of "significant digits" in dividend and divisor, which is derived
3248     by looking at the length of the mantissa. Which is wrong, since it includes
3249     the + sign (oups) and actually gets 2 for '+100' and 4 for '+101'. Oups
3250     again. Thus 124/3 with div_scale=1 will get you '41.3' based on the strange
3251     assumption that 124 has 3 significant digits, while 120/7 will get you
3252     '17', not '17.1' since 120 is thought to have 2 significant digits.
3253     The rounding after the division then uses the remainder and $y to determine
3254     wether it must round up or down.
3255  ?  I have no idea which is the right way. That's why I used a slightly more
3256  ?  simple scheme and tweaked the few failing testcases to match it.
3257
3258 =back
3259
3260 This is how it works now:
3261
3262 =over 2
3263
3264 =item Setting/Accessing
3265
3266   * You can set the A global via Math::BigInt->accuracy() or
3267     Math::BigFloat->accuracy() or whatever class you are using.
3268   * You can also set P globally by using Math::SomeClass->precision() likewise.
3269   * Globals are classwide, and not inherited by subclasses.
3270   * to undefine A, use Math::SomeCLass->accuracy(undef);
3271   * to undefine P, use Math::SomeClass->precision(undef);
3272   * Setting Math::SomeClass->accuracy() clears automatically
3273     Math::SomeClass->precision(), and vice versa.
3274   * To be valid, A must be > 0, P can have any value.
3275   * If P is negative, this means round to the P'th place to the right of the
3276     decimal point; positive values mean to the left of the decimal point.
3277     P of 0 means round to integer.
3278   * to find out the current global A, take Math::SomeClass->accuracy()
3279   * to find out the current global P, take Math::SomeClass->precision()
3280   * use $x->accuracy() respective $x->precision() for the local setting of $x.
3281   * Please note that $x->accuracy() respecive $x->precision() fall back to the
3282     defined globals, when $x's A or P is not set.
3283
3284 =item Creating numbers
3285
3286   * When you create a number, you can give it's desired A or P via:
3287     $x = Math::BigInt->new($number,$A,$P);
3288   * Only one of A or P can be defined, otherwise the result is NaN
3289   * If no A or P is give ($x = Math::BigInt->new($number) form), then the
3290     globals (if set) will be used. Thus changing the global defaults later on
3291     will not change the A or P of previously created numbers (i.e., A and P of
3292     $x will be what was in effect when $x was created)
3293   * If given undef for A and P, B<no> rounding will occur, and the globals will
3294     B<not> be used. This is used by subclasses to create numbers without
3295     suffering rounding in the parent. Thus a subclass is able to have it's own
3296     globals enforced upon creation of a number by using
3297     $x = Math::BigInt->new($number,undef,undef):
3298
3299         use Math::Bigint::SomeSubclass;
3300         use Math::BigInt;
3301
3302         Math::BigInt->accuracy(2);
3303         Math::BigInt::SomeSubClass->accuracy(3);
3304         $x = Math::BigInt::SomeSubClass->new(1234);     
3305
3306     $x is now 1230, and not 1200. A subclass might choose to implement
3307     this otherwise, e.g. falling back to the parent's A and P.
3308
3309 =item Usage
3310
3311   * If A or P are enabled/defined, they are used to round the result of each
3312     operation according to the rules below
3313   * Negative P is ignored in Math::BigInt, since BigInts never have digits
3314     after the decimal point
3315   * Math::BigFloat uses Math::BigInts internally, but setting A or P inside
3316     Math::BigInt as globals should not tamper with the parts of a BigFloat.
3317     Thus a flag is used to mark all Math::BigFloat numbers as 'never round'
3318
3319 =item Precedence
3320
3321   * It only makes sense that a number has only one of A or P at a time.
3322     Since you can set/get both A and P, there is a rule that will practically
3323     enforce only A or P to be in effect at a time, even if both are set.
3324     This is called precedence.
3325   * If two objects are involved in an operation, and one of them has A in
3326     effect, and the other P, this results in an error (NaN).
3327   * A takes precendence over P (Hint: A comes before P). If A is defined, it
3328     is used, otherwise P is used. If neither of them is defined, nothing is
3329     used, i.e. the result will have as many digits as it can (with an
3330     exception for fdiv/fsqrt) and will not be rounded.
3331   * There is another setting for fdiv() (and thus for fsqrt()). If neither of
3332     A or P is defined, fdiv() will use a fallback (F) of $div_scale digits.
3333     If either the dividend's or the divisor's mantissa has more digits than
3334     the value of F, the higher value will be used instead of F.
3335     This is to limit the digits (A) of the result (just consider what would
3336     happen with unlimited A and P in the case of 1/3 :-)
3337   * fdiv will calculate (at least) 4 more digits than required (determined by
3338     A, P or F), and, if F is not used, round the result
3339     (this will still fail in the case of a result like 0.12345000000001 with A
3340     or P of 5, but this can not be helped - or can it?)
3341   * Thus you can have the math done by on Math::Big* class in three modes:
3342     + never round (this is the default):
3343       This is done by setting A and P to undef. No math operation
3344       will round the result, with fdiv() and fsqrt() as exceptions to guard
3345       against overflows. You must explicitely call bround(), bfround() or
3346       round() (the latter with parameters).
3347       Note: Once you have rounded a number, the settings will 'stick' on it
3348       and 'infect' all other numbers engaged in math operations with it, since
3349       local settings have the highest precedence. So, to get SaferRound[tm],
3350       use a copy() before rounding like this:
3351
3352         $x = Math::BigFloat->new(12.34);
3353         $y = Math::BigFloat->new(98.76);
3354         $z = $x * $y;                           # 1218.6984
3355         print $x->copy()->fround(3);            # 12.3 (but A is now 3!)
3356         $z = $x * $y;                           # still 1218.6984, without
3357                                                 # copy would have been 1210!
3358
3359     + round after each op:
3360       After each single operation (except for testing like is_zero()), the
3361       method round() is called and the result is rounded appropriately. By
3362       setting proper values for A and P, you can have all-the-same-A or
3363       all-the-same-P modes. For example, Math::Currency might set A to undef,
3364       and P to -2, globally.
3365
3366  ?Maybe an extra option that forbids local A & P settings would be in order,
3367  ?so that intermediate rounding does not 'poison' further math? 
3368
3369 =item Overriding globals
3370
3371   * you will be able to give A, P and R as an argument to all the calculation
3372     routines; the second parameter is A, the third one is P, and the fourth is
3373     R (shift right by one for binary operations like badd). P is used only if
3374     the first parameter (A) is undefined. These three parameters override the
3375     globals in the order detailed as follows, i.e. the first defined value
3376     wins:
3377     (local: per object, global: global default, parameter: argument to sub)
3378       + parameter A
3379       + parameter P
3380       + local A (if defined on both of the operands: smaller one is taken)
3381       + local P (if defined on both of the operands: bigger one is taken)
3382       + global A
3383       + global P
3384       + global F
3385   * fsqrt() will hand its arguments to fdiv(), as it used to, only now for two
3386     arguments (A and P) instead of one
3387
3388 =item Local settings
3389
3390   * You can set A and P locally by using $x->accuracy() and $x->precision()
3391     and thus force different A and P for different objects/numbers.
3392   * Setting A or P this way immediately rounds $x to the new value.
3393   * $x->accuracy() clears $x->precision(), and vice versa.
3394
3395 =item Rounding
3396
3397   * the rounding routines will use the respective global or local settings.
3398     fround()/bround() is for accuracy rounding, while ffround()/bfround()
3399     is for precision
3400   * the two rounding functions take as the second parameter one of the
3401     following rounding modes (R):
3402     'even', 'odd', '+inf', '-inf', 'zero', 'trunc'
3403   * you can set and get the global R by using Math::SomeClass->round_mode()
3404     or by setting $Math::SomeClass::round_mode
3405   * after each operation, $result->round() is called, and the result may
3406     eventually be rounded (that is, if A or P were set either locally,
3407     globally or as parameter to the operation)
3408   * to manually round a number, call $x->round($A,$P,$round_mode);
3409     this will round the number by using the appropriate rounding function
3410     and then normalize it.
3411   * rounding modifies the local settings of the number:
3412
3413         $x = Math::BigFloat->new(123.456);
3414         $x->accuracy(5);
3415         $x->bround(4);
3416
3417     Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy()
3418     will be 4 from now on.
3419
3420 =item Default values
3421
3422   * R: 'even'
3423   * F: 40
3424   * A: undef
3425   * P: undef
3426
3427 =item Remarks
3428
3429   * The defaults are set up so that the new code gives the same results as
3430     the old code (except in a few cases on fdiv):
3431     + Both A and P are undefined and thus will not be used for rounding
3432       after each operation.
3433     + round() is thus a no-op, unless given extra parameters A and P
3434
3435 =back
3436
3437 =head1 INTERNALS
3438
3439 The actual numbers are stored as unsigned big integers (with seperate sign).
3440 You should neither care about nor depend on the internal representation; it
3441 might change without notice. Use only method calls like C<< $x->sign(); >>
3442 instead relying on the internal hash keys like in C<< $x->{sign}; >>. 
3443
3444 =head2 MATH LIBRARY
3445
3446 Math with the numbers is done (by default) by a module called
3447 Math::BigInt::Calc. This is equivalent to saying:
3448
3449         use Math::BigInt lib => 'Calc';
3450
3451 You can change this by using:
3452
3453         use Math::BigInt lib => 'BitVect';
3454
3455 The following would first try to find Math::BigInt::Foo, then
3456 Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
3457
3458         use Math::BigInt lib => 'Foo,Math::BigInt::Bar';
3459
3460 Calc.pm uses as internal format an array of elements of some decimal base
3461 (usually 1e5 or 1e7) with the least significant digit first, while BitVect.pm
3462 uses a bit vector of base 2, most significant bit first. Other modules might
3463 use even different means of representing the numbers. See the respective
3464 module documentation for further details.
3465
3466 =head2 SIGN
3467
3468 The sign is either '+', '-', 'NaN', '+inf' or '-inf' and stored seperately.
3469
3470 A sign of 'NaN' is used to represent the result when input arguments are not
3471 numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively
3472 minus infinity. You will get '+inf' when dividing a positive number by 0, and
3473 '-inf' when dividing any negative number by 0.
3474
3475 =head2 mantissa(), exponent() and parts()
3476
3477 C<mantissa()> and C<exponent()> return the said parts of the BigInt such
3478 that:
3479
3480         $m = $x->mantissa();
3481         $e = $x->exponent();
3482         $y = $m * ( 10 ** $e );
3483         print "ok\n" if $x == $y;
3484
3485 C<< ($m,$e) = $x->parts() >> is just a shortcut that gives you both of them
3486 in one go. Both the returned mantissa and exponent have a sign.
3487
3488 Currently, for BigInts C<$e> will be always 0, except for NaN, +inf and -inf,
3489 where it will be NaN; and for $x == 0, where it will be 1
3490 (to be compatible with Math::BigFloat's internal representation of a zero as
3491 C<0E1>).
3492
3493 C<$m> will always be a copy of the original number. The relation between $e
3494 and $m might change in the future, but will always be equivalent in a
3495 numerical sense, e.g. $m might get minimized.
3496
3497 =head1 EXAMPLES
3498  
3499   use Math::BigInt;
3500
3501   sub bint { Math::BigInt->new(shift); }
3502
3503   $x = Math::BigInt->bstr("1234")       # string "1234"
3504   $x = "$x";                            # same as bstr()
3505   $x = Math::BigInt->bneg("1234");      # Bigint "-1234"
3506   $x = Math::BigInt->babs("-12345");    # Bigint "12345"
3507   $x = Math::BigInt->bnorm("-0 00");    # BigInt "0"
3508   $x = bint(1) + bint(2);               # BigInt "3"
3509   $x = bint(1) + "2";                   # ditto (auto-BigIntify of "2")
3510   $x = bint(1);                         # BigInt "1"
3511   $x = $x + 5 / 2;                      # BigInt "3"
3512   $x = $x ** 3;                         # BigInt "27"
3513   $x *= 2;                              # BigInt "54"
3514   $x = Math::BigInt->new(0);            # BigInt "0"
3515   $x--;                                 # BigInt "-1"
3516   $x = Math::BigInt->badd(4,5)          # BigInt "9"
3517   print $x->bsstr();                    # 9e+0
3518
3519 Examples for rounding:
3520
3521   use Math::BigFloat;
3522   use Test;
3523
3524   $x = Math::BigFloat->new(123.4567);
3525   $y = Math::BigFloat->new(123.456789);
3526   Math::BigFloat->accuracy(4);          # no more A than 4
3527
3528   ok ($x->copy()->fround(),123.4);      # even rounding
3529   print $x->copy()->fround(),"\n";      # 123.4
3530   Math::BigFloat->round_mode('odd');    # round to odd
3531   print $x->copy()->fround(),"\n";      # 123.5
3532   Math::BigFloat->accuracy(5);          # no more A than 5
3533   Math::BigFloat->round_mode('odd');    # round to odd
3534   print $x->copy()->fround(),"\n";      # 123.46
3535   $y = $x->copy()->fround(4),"\n";      # A = 4: 123.4
3536   print "$y, ",$y->accuracy(),"\n";     # 123.4, 4
3537
3538   Math::BigFloat->accuracy(undef);      # A not important now
3539   Math::BigFloat->precision(2);         # P important
3540   print $x->copy()->bnorm(),"\n";       # 123.46
3541   print $x->copy()->fround(),"\n";      # 123.46
3542
3543 Examples for converting:
3544
3545   my $x = Math::BigInt->new('0b1'.'01' x 123);
3546   print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n";
3547
3548 =head1 Autocreating constants
3549
3550 After C<use Math::BigInt ':constant'> all the B<integer> decimal, hexadecimal
3551 and binary constants in the given scope are converted to C<Math::BigInt>.
3552 This conversion happens at compile time. 
3553
3554 In particular,
3555
3556   perl -MMath::BigInt=:constant -e 'print 2**100,"\n"'
3557
3558 prints the integer value of C<2**100>. Note that without conversion of 
3559 constants the expression 2**100 will be calculated as perl scalar.
3560
3561 Please note that strings and floating point constants are not affected,
3562 so that
3563
3564         use Math::BigInt qw/:constant/;
3565
3566         $x = 1234567890123456789012345678901234567890
3567                 + 123456789123456789;
3568         $y = '1234567890123456789012345678901234567890'
3569                 + '123456789123456789';
3570
3571 do not work. You need an explicit Math::BigInt->new() around one of the
3572 operands. You should also quote large constants to protect loss of precision:
3573
3574         use Math::Bigint;
3575
3576         $x = Math::BigInt->new('1234567889123456789123456789123456789');
3577
3578 Without the quotes Perl would convert the large number to a floating point
3579 constant at compile time and then hand the result to BigInt, which results in
3580 an truncated result or a NaN.
3581
3582 This also applies to integers that look like floating point constants:
3583
3584         use Math::BigInt ':constant';
3585
3586         print ref(123e2),"\n";
3587         print ref(123.2e2),"\n";
3588
3589 will print nothing but newlines. Use either L<bignum> or L<Math::BigFloat>
3590 to get this to work.
3591
3592 =head1 PERFORMANCE
3593
3594 Using the form $x += $y; etc over $x = $x + $y is faster, since a copy of $x
3595 must be made in the second case. For long numbers, the copy can eat up to 20%
3596 of the work (in the case of addition/subtraction, less for
3597 multiplication/division). If $y is very small compared to $x, the form
3598 $x += $y is MUCH faster than $x = $x + $y since making the copy of $x takes
3599 more time then the actual addition.
3600
3601 With a technique called copy-on-write, the cost of copying with overload could
3602 be minimized or even completely avoided. A test implementation of COW did show
3603 performance gains for overloaded math, but introduced a performance loss due
3604 to a constant overhead for all other operatons.
3605
3606 The rewritten version of this module is slower on certain operations, like
3607 new(), bstr() and numify(). The reason are that it does now more work and
3608 handles more cases. The time spent in these operations is usually gained in
3609 the other operations so that programs on the average should get faster. If
3610 they don't, please contect the author.
3611
3612 Some operations may be slower for small numbers, but are significantly faster
3613 for big numbers. Other operations are now constant (O(1), like bneg(), babs()
3614 etc), instead of O(N) and thus nearly always take much less time. These
3615 optimizations were done on purpose.
3616
3617 If you find the Calc module to slow, try to install any of the replacement
3618 modules and see if they help you. 
3619
3620 =head2 Alternative math libraries
3621
3622 You can use an alternative library to drive Math::BigInt via:
3623
3624         use Math::BigInt lib => 'Module';
3625
3626 See L<MATH LIBRARY> for more information.
3627
3628 For more benchmark results see L<http://bloodgate.com/perl/benchmarks.html>.
3629
3630 =head2 SUBCLASSING
3631
3632 =head1 Subclassing Math::BigInt
3633
3634 The basic design of Math::BigInt allows simple subclasses with very little
3635 work, as long as a few simple rules are followed:
3636
3637 =over 2
3638
3639 =item *
3640
3641 The public API must remain consistent, i.e. if a sub-class is overloading
3642 addition, the sub-class must use the same name, in this case badd(). The
3643 reason for this is that Math::BigInt is optimized to call the object methods
3644 directly.
3645
3646 =item *
3647
3648 The private object hash keys like C<$x->{sign}> may not be changed, but
3649 additional keys can be added, like C<$x->{_custom}>.
3650
3651 =item *
3652
3653 Accessor functions are available for all existing object hash keys and should
3654 be used instead of directly accessing the internal hash keys. The reason for
3655 this is that Math::BigInt itself has a pluggable interface which permits it
3656 to support different storage methods.
3657
3658 =back
3659
3660 More complex sub-classes may have to replicate more of the logic internal of
3661 Math::BigInt if they need to change more basic behaviors. A subclass that
3662 needs to merely change the output only needs to overload C<bstr()>. 
3663
3664 All other object methods and overloaded functions can be directly inherited
3665 from the parent class.
3666
3667 At the very minimum, any subclass will need to provide it's own C<new()> and can
3668 store additional hash keys in the object. There are also some package globals
3669 that must be defined, e.g.:
3670
3671   # Globals
3672   $accuracy = undef;
3673   $precision = -2;       # round to 2 decimal places
3674   $round_mode = 'even';
3675   $div_scale = 40;
3676
3677 Additionally, you might want to provide the following two globals to allow
3678 auto-upgrading and auto-downgrading to work correctly:
3679
3680   $upgrade = undef;
3681   $downgrade = undef;
3682
3683 This allows Math::BigInt to correctly retrieve package globals from the 
3684 subclass, like C<$SubClass::precision>.  See t/Math/BigInt/Subclass.pm or
3685 t/Math/BigFloat/SubClass.pm completely functional subclass examples.
3686
3687 Don't forget to 
3688
3689         use overload;
3690
3691 in your subclass to automatically inherit the overloading from the parent. If
3692 you like, you can change part of the overloading, look at Math::String for an
3693 example.
3694
3695 =head1 UPGRADING
3696
3697 When used like this:
3698
3699         use Math::BigInt upgrade => 'Foo::Bar';
3700
3701 certain operations will 'upgrade' their calculation and thus the result to
3702 the class Foo::Bar. Usually this is used in conjunction with Math::BigFloat:
3703
3704         use Math::BigInt upgrade => 'Math::BigFloat';
3705
3706 As a shortcut, you can use the module C<bignum>:
3707
3708         use bignum;
3709
3710 Also good for oneliners:
3711
3712         perl -Mbignum -le 'print 2 ** 255'
3713
3714 This makes it possible to mix arguments of different classes (as in 2.5 + 2)
3715 as well es preserve accuracy (as in sqrt(3)).
3716
3717 Beware: This feature is not fully implemented yet.
3718
3719 =head2 Auto-upgrade
3720
3721 The following methods upgrade themselves unconditionally; that is if upgrade
3722 is in effect, they will always hand up their work:
3723
3724 =over 2
3725
3726 =item bsqrt()
3727
3728 =item div()
3729
3730 =item blog()
3731
3732 =back
3733
3734 Beware: This list is not complete.
3735
3736 All other methods upgrade themselves only when one (or all) of their
3737 arguments are of the class mentioned in $upgrade (This might change in later
3738 versions to a more sophisticated scheme):
3739
3740 =head1 BUGS
3741
3742 =over 2
3743
3744 =item Out of Memory!
3745
3746 Under Perl prior to 5.6.0 having an C<use Math::BigInt ':constant';> and 
3747 C<eval()> in your code will crash with "Out of memory". This is probably an
3748 overload/exporter bug. You can workaround by not having C<eval()> 
3749 and ':constant' at the same time or upgrade your Perl to a newer version.
3750
3751 =item Fails to load Calc on Perl prior 5.6.0
3752
3753 Since eval(' use ...') can not be used in conjunction with ':constant', BigInt
3754 will fall back to eval { require ... } when loading the math lib on Perls
3755 prior to 5.6.0. This simple replaces '::' with '/' and thus might fail on
3756 filesystems using a different seperator.  
3757
3758 =back
3759
3760 =head1 CAVEATS
3761
3762 Some things might not work as you expect them. Below is documented what is
3763 known to be troublesome:
3764
3765 =over 1
3766
3767 =item stringify, bstr(), bsstr() and 'cmp'
3768
3769 Both stringify and bstr() now drop the leading '+'. The old code would return
3770 '+3', the new returns '3'. This is to be consistent with Perl and to make
3771 cmp (especially with overloading) to work as you expect. It also solves
3772 problems with Test.pm, it's ok() uses 'eq' internally. 
3773
3774 Mark said, when asked about to drop the '+' altogether, or make only cmp work:
3775
3776         I agree (with the first alternative), don't add the '+' on positive
3777         numbers.  It's not as important anymore with the new internal 
3778         form for numbers.  It made doing things like abs and neg easier,
3779         but those have to be done differently now anyway.
3780
3781 So, the following examples will now work all as expected:
3782
3783         use Test;
3784         BEGIN { plan tests => 1 }
3785         use Math::BigInt;
3786
3787         my $x = new Math::BigInt 3*3;
3788         my $y = new Math::BigInt 3*3;
3789
3790         ok ($x,3*3);
3791         print "$x eq 9" if $x eq $y;
3792         print "$x eq 9" if $x eq '9';
3793         print "$x eq 9" if $x eq 3*3;
3794
3795 Additionally, the following still works:
3796         
3797         print "$x == 9" if $x == $y;
3798         print "$x == 9" if $x == 9;
3799         print "$x == 9" if $x == 3*3;
3800
3801 There is now a C<bsstr()> method to get the string in scientific notation aka
3802 C<1e+2> instead of C<100>. Be advised that overloaded 'eq' always uses bstr()
3803 for comparisation, but Perl will represent some numbers as 100 and others
3804 as 1e+308. If in doubt, convert both arguments to Math::BigInt before doing eq:
3805
3806         use Test;
3807         BEGIN { plan tests => 3 }
3808         use Math::BigInt;
3809
3810         $x = Math::BigInt->new('1e56'); $y = 1e56;
3811         ok ($x,$y);                     # will fail
3812         ok ($x->bsstr(),$y);            # okay
3813         $y = Math::BigInt->new($y);
3814         ok ($x,$y);                     # okay
3815
3816 Alternatively, simple use <=> for comparisations, that will get it always
3817 right. There is not yet a way to get a number automatically represented as
3818 a string that matches exactly the way Perl represents it.
3819
3820 =item int()
3821
3822 C<int()> will return (at least for Perl v5.7.1 and up) another BigInt, not a 
3823 Perl scalar:
3824
3825         $x = Math::BigInt->new(123);
3826         $y = int($x);                           # BigInt 123
3827         $x = Math::BigFloat->new(123.45);
3828         $y = int($x);                           # BigInt 123
3829
3830 In all Perl versions you can use C<as_number()> for the same effect:
3831
3832         $x = Math::BigFloat->new(123.45);
3833         $y = $x->as_number();                   # BigInt 123
3834
3835 This also works for other subclasses, like Math::String.
3836
3837 It is yet unlcear whether overloaded int() should return a scalar or a BigInt.
3838
3839 =item length
3840
3841 The following will probably not do what you expect:
3842
3843         $c = Math::BigInt->new(123);
3844         print $c->length(),"\n";                # prints 30
3845
3846 It prints both the number of digits in the number and in the fraction part
3847 since print calls C<length()> in list context. Use something like: 
3848         
3849         print scalar $c->length(),"\n";         # prints 3 
3850
3851 =item bdiv
3852
3853 The following will probably not do what you expect:
3854
3855         print $c->bdiv(10000),"\n";
3856
3857 It prints both quotient and remainder since print calls C<bdiv()> in list
3858 context. Also, C<bdiv()> will modify $c, so be carefull. You probably want
3859 to use
3860         
3861         print $c / 10000,"\n";
3862         print scalar $c->bdiv(10000),"\n";  # or if you want to modify $c
3863
3864 instead.
3865
3866 The quotient is always the greatest integer less than or equal to the
3867 real-valued quotient of the two operands, and the remainder (when it is
3868 nonzero) always has the same sign as the second operand; so, for
3869 example,
3870
3871           1 / 4  => ( 0, 1)
3872           1 / -4 => (-1,-3)
3873          -3 / 4  => (-1, 1)
3874          -3 / -4 => ( 0,-3)
3875         -11 / 2  => (-5,1)
3876          11 /-2  => (-5,-1)
3877
3878 As a consequence, the behavior of the operator % agrees with the
3879 behavior of Perl's built-in % operator (as documented in the perlop
3880 manpage), and the equation
3881
3882         $x == ($x / $y) * $y + ($x % $y)
3883
3884 holds true for any $x and $y, which justifies calling the two return
3885 values of bdiv() the quotient and remainder. The only exception to this rule
3886 are when $y == 0 and $x is negative, then the remainder will also be
3887 negative. See below under "infinity handling" for the reasoning behing this.
3888
3889 Perl's 'use integer;' changes the behaviour of % and / for scalars, but will
3890 not change BigInt's way to do things. This is because under 'use integer' Perl
3891 will do what the underlying C thinks is right and this is different for each
3892 system. If you need BigInt's behaving exactly like Perl's 'use integer', bug
3893 the author to implement it ;)
3894
3895 =item infinity handling
3896
3897 Here are some examples that explain the reasons why certain results occur while
3898 handling infinity:
3899
3900 The following table shows the result of the division and the remainder, so that
3901 the equation above holds true. Some "ordinary" cases are strewn in to show more
3902 clearly the reasoning:
3903
3904         A /  B  =   C,     R so that C *    B +    R =    A
3905      =========================================================
3906         5 /   8 =   0,     5         0 *    8 +    5 =    5
3907         0 /   8 =   0,     0         0 *    8 +    0 =    0
3908         0 / inf =   0,     0         0 *  inf +    0 =    0
3909         0 /-inf =   0,     0         0 * -inf +    0 =    0
3910         5 / inf =   0,     5         0 *  inf +    5 =    5
3911         5 /-inf =   0,     5         0 * -inf +    5 =    5
3912         -5/ inf =   0,    -5         0 *  inf +   -5 =   -5
3913         -5/-inf =   0,    -5         0 * -inf +   -5 =   -5
3914        inf/   5 =  inf,    0       inf *    5 +    0 =  inf
3915       -inf/   5 = -inf,    0      -inf *    5 +    0 = -inf
3916        inf/  -5 = -inf,    0      -inf *   -5 +    0 =  inf
3917       -inf/  -5 =  inf,    0       inf *   -5 +    0 = -inf
3918          5/   5 =    1,    0         1 *    5 +    0 =    5
3919         -5/  -5 =    1,    0         1 *   -5 +    0 =   -5
3920        inf/ inf =    1,    0         1 *  inf +    0 =  inf
3921       -inf/-inf =    1,    0         1 * -inf +    0 = -inf
3922        inf/-inf =   -1,    0        -1 * -inf +    0 =  inf
3923       -inf/ inf =   -1,    0         1 * -inf +    0 = -inf
3924          8/   0 =  inf,    8       inf *    0 +    8 =    8 
3925        inf/   0 =  inf,  inf       inf *    0 +  inf =  inf 
3926          0/   0 =  NaN
3927
3928 These cases below violate the "remainder has the sign of the second of the two
3929 arguments", since they wouldn't match up otherwise.
3930
3931         A /  B  =   C,     R so that C *    B +    R =    A
3932      ========================================================
3933       -inf/   0 = -inf, -inf      -inf *    0 +  inf = -inf 
3934         -8/   0 = -inf,   -8      -inf *    0 +    8 = -8 
3935
3936 =item Modifying and =
3937
3938 Beware of:
3939
3940         $x = Math::BigFloat->new(5);
3941         $y = $x;
3942
3943 It will not do what you think, e.g. making a copy of $x. Instead it just makes
3944 a second reference to the B<same> object and stores it in $y. Thus anything
3945 that modifies $x (except overloaded operators) will modify $y, and vice versa.
3946 Or in other words, C<=> is only safe if you modify your BigInts only via
3947 overloaded math. As soon as you use a method call it breaks:
3948
3949         $x->bmul(2);
3950         print "$x, $y\n";       # prints '10, 10'
3951
3952 If you want a true copy of $x, use:
3953
3954         $y = $x->copy();
3955
3956 You can also chain the calls like this, this will make first a copy and then
3957 multiply it by 2:
3958
3959         $y = $x->copy()->bmul(2);
3960
3961 See also the documentation for overload.pm regarding C<=>.
3962
3963 =item bpow
3964
3965 C<bpow()> (and the rounding functions) now modifies the first argument and
3966 returns it, unlike the old code which left it alone and only returned the
3967 result. This is to be consistent with C<badd()> etc. The first three will
3968 modify $x, the last one won't:
3969
3970         print bpow($x,$i),"\n";         # modify $x
3971         print $x->bpow($i),"\n";        # ditto
3972         print $x **= $i,"\n";           # the same
3973         print $x ** $i,"\n";            # leave $x alone 
3974
3975 The form C<$x **= $y> is faster than C<$x = $x ** $y;>, though.
3976
3977 =item Overloading -$x
3978
3979 The following:
3980
3981         $x = -$x;
3982
3983 is slower than
3984
3985         $x->bneg();
3986
3987 since overload calls C<sub($x,0,1);> instead of C<neg($x)>. The first variant
3988 needs to preserve $x since it does not know that it later will get overwritten.
3989 This makes a copy of $x and takes O(N), but $x->bneg() is O(1).
3990
3991 With Copy-On-Write, this issue would be gone, but C-o-W is not implemented
3992 since it is slower for all other things.
3993
3994 =item Mixing different object types
3995
3996 In Perl you will get a floating point value if you do one of the following:
3997
3998         $float = 5.0 + 2;
3999         $float = 2 + 5.0;
4000         $float = 5 / 2;
4001
4002 With overloaded math, only the first two variants will result in a BigFloat:
4003
4004         use Math::BigInt;
4005         use Math::BigFloat;
4006         
4007         $mbf = Math::BigFloat->new(5);
4008         $mbi2 = Math::BigInteger->new(5);
4009         $mbi = Math::BigInteger->new(2);
4010
4011                                         # what actually gets called:
4012         $float = $mbf + $mbi;           # $mbf->badd()
4013         $float = $mbf / $mbi;           # $mbf->bdiv()
4014         $integer = $mbi + $mbf;         # $mbi->badd()
4015         $integer = $mbi2 / $mbi;        # $mbi2->bdiv()
4016         $integer = $mbi2 / $mbf;        # $mbi2->bdiv()
4017
4018 This is because math with overloaded operators follows the first (dominating)
4019 operand, and the operation of that is called and returns thus the result. So,
4020 Math::BigInt::bdiv() will always return a Math::BigInt, regardless whether
4021 the result should be a Math::BigFloat or the second operant is one.
4022
4023 To get a Math::BigFloat you either need to call the operation manually,
4024 make sure the operands are already of the proper type or casted to that type
4025 via Math::BigFloat->new():
4026         
4027         $float = Math::BigFloat->new($mbi2) / $mbi;     # = 2.5
4028
4029 Beware of simple "casting" the entire expression, this would only convert
4030 the already computed result:
4031
4032         $float = Math::BigFloat->new($mbi2 / $mbi);     # = 2.0 thus wrong!
4033
4034 Beware also of the order of more complicated expressions like:
4035
4036         $integer = ($mbi2 + $mbi) / $mbf;               # int / float => int
4037         $integer = $mbi2 / Math::BigFloat->new($mbi);   # ditto
4038
4039 If in doubt, break the expression into simpler terms, or cast all operands
4040 to the desired resulting type.
4041
4042 Scalar values are a bit different, since:
4043         
4044         $float = 2 + $mbf;
4045         $float = $mbf + 2;
4046
4047 will both result in the proper type due to the way the overloaded math works.
4048
4049 This section also applies to other overloaded math packages, like Math::String.
4050
4051 One solution to you problem might be L<autoupgrading|upgrading>.
4052
4053 =item bsqrt()
4054
4055 C<bsqrt()> works only good if the result is a big integer, e.g. the square
4056 root of 144 is 12, but from 12 the square root is 3, regardless of rounding
4057 mode.
4058
4059 If you want a better approximation of the square root, then use:
4060
4061         $x = Math::BigFloat->new(12);
4062         Math::BigFloat->precision(0);
4063         Math::BigFloat->round_mode('even');
4064         print $x->copy->bsqrt(),"\n";           # 4
4065
4066         Math::BigFloat->precision(2);
4067         print $x->bsqrt(),"\n";                 # 3.46
4068         print $x->bsqrt(3),"\n";                # 3.464
4069
4070 =item brsft()
4071
4072 For negative numbers in base see also L<brsft|brsft>.
4073
4074 =back
4075
4076 =head1 LICENSE
4077
4078 This program is free software; you may redistribute it and/or modify it under
4079 the same terms as Perl itself.
4080
4081 =head1 SEE ALSO
4082
4083 L<Math::BigFloat> and L<Math::Big> as well as L<Math::BigInt::BitVect>,
4084 L<Math::BigInt::Pari> and  L<Math::BigInt::GMP>.
4085
4086 The package at
4087 L<http://search.cpan.org/search?mode=module&query=Math%3A%3ABigInt> contains
4088 more documentation including a full version history, testcases, empty
4089 subclass files and benchmarks.
4090
4091 =head1 AUTHORS
4092
4093 Original code by Mark Biggar, overloaded interface by Ilya Zakharevich.
4094 Completely rewritten by Tels http://bloodgate.com in late 2000, 2001.
4095
4096 =cut