xref: /openbsd-src/gnu/usr.bin/perl/cpan/Math-BigInt/t/Math/BigInt/Lib/Minimal.pm (revision 46035553bfdd96e63c94e32da0210227ec2e3cf1)
1# This is a rather minimalistic library, whose purpose is to test inheritance
2# from its parent class.
3
4package Math::BigInt::Lib::Minimal;
5
6use 5.006001;
7use strict;
8use warnings;
9
10use Carp;
11use Math::BigInt::Lib;
12
13our @ISA = ('Math::BigInt::Lib');
14
15#my $BASE_LEN = 4;
16my $BASE_LEN = 9;
17my $BASE     = 0 + ("1" . ("0" x $BASE_LEN));
18my $MAX_VAL  = $BASE - 1;
19
20# Do we need api_version() at all, now that we have a virtual parent class that
21# will provide any missing methods? Fixme!
22
23sub api_version () { 2; }
24
25sub _new {
26    my ($class, $str) = @_;
27    croak "Invalid input string '$str'" unless $str =~ /^([1-9]\d*|0)\z/;
28
29    my $n = length $str;
30    my $p = int($n / $BASE_LEN);
31    my $q = $n % $BASE_LEN;
32
33    my $format = $] < 5.9008 ? "a$BASE_LEN" x $p
34                             : "(a$BASE_LEN)*";
35    $format = "a$q" . $format if $q > 0;
36
37    my $self = [ reverse(map { 0 + $_ } unpack($format, $str)) ];
38    return bless $self, $class;
39}
40
41##############################################################################
42# convert back to string and number
43
44sub _str {
45    my ($class, $x) = @_;
46    my $idx = $#$x;             # index of last element
47
48    # Handle first one differently, since it should not have any leading zeros.
49
50    my $str = int($x->[$idx]);
51
52    if ($idx > 0) {
53        my $z = '0' x ($BASE_LEN - 1);
54        while (--$idx >= 0) {
55            $str .= substr($z . $x->[$idx], -$BASE_LEN);
56        }
57    }
58    $str;
59}
60
61##############################################################################
62# actual math code
63
64sub _add {
65    # (ref to int_num_array, ref to int_num_array)
66    #
67    # Routine to add two base 1eX numbers stolen from Knuth Vol 2 Algorithm A
68    # pg 231. There are separate routines to add and sub as per Knuth pg 233.
69    # This routine modifies array x, but not y.
70
71    my ($c, $x, $y) = @_;
72
73    # $x + 0 => $x
74
75    return $x if @$y == 1 && $y->[0] == 0;
76
77    # 0 + $y => $y->copy
78
79    if (@$x == 1 && $x->[0] == 0) {
80        @$x = @$y;
81        return $x;
82    }
83
84    # For each in Y, add Y to X and carry. If after that, something is left in
85    # X, foreach in X add carry to X and then return X, carry. Trades one
86    # "$j++" for having to shift arrays.
87
88    my $i;
89    my $car = 0;
90    my $j = 0;
91    for $i (@$y) {
92        $x->[$j] -= $BASE if $car = (($x->[$j] += $i + $car) >= $BASE) ? 1 : 0;
93        $j++;
94    }
95    while ($car != 0) {
96        $x->[$j] -= $BASE if $car = (($x->[$j] += $car) >= $BASE) ? 1 : 0;
97        $j++;
98    }
99
100    $x;
101}
102
103sub _sub {
104    # (ref to int_num_array, ref to int_num_array, swap)
105    #
106    # Subtract base 1eX numbers -- stolen from Knuth Vol 2 pg 232, $x > $y
107    # subtract Y from X by modifying x in place
108    my ($c, $sx, $sy, $s) = @_;
109
110    my $car = 0;
111    my $i;
112    my $j = 0;
113    if (!$s) {
114        for $i (@$sx) {
115            last unless defined $sy->[$j] || $car;
116            $i += $BASE if $car = (($i -= ($sy->[$j] || 0) + $car) < 0);
117            $j++;
118        }
119        # might leave leading zeros, so fix that
120        return __strip_zeros($sx);
121    }
122    for $i (@$sx) {
123        # We can't do an early out if $x < $y, since we need to copy the high
124        # chunks from $y. Found by Bob Mathews.
125        #last unless defined $sy->[$j] || $car;
126        $sy->[$j] += $BASE
127          if $car = ($sy->[$j] = $i - ($sy->[$j] || 0) - $car) < 0;
128        $j++;
129    }
130    # might leave leading zeros, so fix that
131    __strip_zeros($sy);
132}
133
134# The following _mul function is an exact copy of _mul_use_div_64 in
135# Math::BigInt::Calc.
136
137sub _mul {
138    # (ref to int_num_array, ref to int_num_array)
139    # multiply two numbers in internal representation
140    # modifies first arg, second need not be different from first
141    # works for 64 bit integer with "use integer"
142    my ($c, $xv, $yv) = @_;
143
144    use integer;
145    if (@$yv == 1) {
146        # shortcut for two small numbers, also handles $x == 0
147        if (@$xv == 1) {
148            # shortcut for two very short numbers (improved by Nathan Zook)
149            # works also if xv and yv are the same reference, and handles also $x == 0
150            if (($xv->[0] *= $yv->[0]) >= $BASE) {
151                $xv->[0] =
152                  $xv->[0] - ($xv->[1] = $xv->[0] / $BASE) * $BASE;
153            }
154            return $xv;
155        }
156        # $x * 0 => 0
157        if ($yv->[0] == 0) {
158            @$xv = (0);
159            return $xv;
160        }
161        # multiply a large number a by a single element one, so speed up
162        my $y = $yv->[0];
163        my $car = 0;
164        foreach my $i (@$xv) {
165            #$i = $i * $y + $car; $car = $i / $BASE; $i -= $car * $BASE;
166            $i = $i * $y + $car;
167            $i -= ($car = $i / $BASE) * $BASE;
168        }
169        push @$xv, $car if $car != 0;
170        return $xv;
171    }
172    # shortcut for result $x == 0 => result = 0
173    return $xv if ( ((@$xv == 1) && ($xv->[0] == 0)) );
174
175    # since multiplying $x with $x fails, make copy in this case
176    $yv = $c->_copy($xv) if $xv == $yv; # same references?
177
178    my @prod = ();
179    my ($prod, $car, $cty, $xi, $yi);
180    for $xi (@$xv) {
181        $car = 0;
182        $cty = 0;
183        # looping through this if $xi == 0 is silly - so optimize it away!
184        $xi = (shift @prod || 0), next if $xi == 0;
185        for $yi (@$yv) {
186            $prod = $xi * $yi + ($prod[$cty] || 0) + $car;
187            $prod[$cty++] = $prod - ($car = $prod / $BASE) * $BASE;
188        }
189        $prod[$cty] += $car if $car; # need really to check for 0?
190        $xi = shift @prod || 0;      # || 0 makes v5.005_3 happy
191    }
192    push @$xv, @prod;
193    $xv;
194}
195
196# The following _div function is an exact copy of _div_use_div_64 in
197# Math::BigInt::Calc.
198
199sub _div {
200    # ref to array, ref to array, modify first array and return remainder if
201    # in list context
202    # This version works on 64 bit integers
203    my ($c, $x, $yorg) = @_;
204
205    use integer;
206    # the general div algorithm here is about O(N*N) and thus quite slow, so
207    # we first check for some special cases and use shortcuts to handle them.
208
209    # This works, because we store the numbers in a chunked format where each
210    # element contains 5..7 digits (depending on system).
211
212    # if both numbers have only one element:
213    if (@$x == 1 && @$yorg == 1) {
214        # shortcut, $yorg and $x are two small numbers
215        if (wantarray) {
216            my $rem = [ $x->[0] % $yorg->[0] ];
217            bless $rem, $c;
218            $x->[0] = int($x->[0] / $yorg->[0]);
219            return ($x, $rem);
220        } else {
221            $x->[0] = int($x->[0] / $yorg->[0]);
222            return $x;
223        }
224    }
225    # if x has more than one, but y has only one element:
226    if (@$yorg == 1) {
227        my $rem;
228        $rem = $c->_mod($c->_copy($x), $yorg) if wantarray;
229
230        # shortcut, $y is < $BASE
231        my $j = @$x;
232        my $r = 0;
233        my $y = $yorg->[0];
234        my $b;
235        while ($j-- > 0) {
236            $b = $r * $BASE + $x->[$j];
237            $x->[$j] = int($b/$y);
238            $r = $b % $y;
239        }
240        pop @$x if @$x > 1 && $x->[-1] == 0; # splice up a leading zero
241        return ($x, $rem) if wantarray;
242        return $x;
243    }
244    # now x and y have more than one element
245
246    # check whether y has more elements than x, if yet, the result will be 0
247    if (@$yorg > @$x) {
248        my $rem;
249        $rem = $c->_copy($x) if wantarray;    # make copy
250        @$x = 0;                        # set to 0
251        return ($x, $rem) if wantarray; # including remainder?
252        return $x;                      # only x, which is [0] now
253    }
254    # check whether the numbers have the same number of elements, in that case
255    # the result will fit into one element and can be computed efficiently
256    if (@$yorg == @$x) {
257        my $rem;
258        # if $yorg has more digits than $x (it's leading element is longer than
259        # the one from $x), the result will also be 0:
260        if (length(int($yorg->[-1])) > length(int($x->[-1]))) {
261            $rem = $c->_copy($x) if wantarray;     # make copy
262            @$x = 0;                          # set to 0
263            return ($x, $rem) if wantarray; # including remainder?
264            return $x;
265        }
266        # now calculate $x / $yorg
267
268        if (length(int($yorg->[-1])) == length(int($x->[-1]))) {
269            # same length, so make full compare
270
271            my $a = 0;
272            my $j = @$x - 1;
273            # manual way (abort if unequal, good for early ne)
274            while ($j >= 0) {
275                last if ($a = $x->[$j] - $yorg->[$j]);
276                $j--;
277            }
278            # $a contains the result of the compare between X and Y
279            # a < 0: x < y, a == 0: x == y, a > 0: x > y
280            if ($a <= 0) {
281                $rem = $c->_zero();                  # a = 0 => x == y => rem 0
282                $rem = $c->_copy($x) if $a != 0;       # a < 0 => x < y => rem = x
283                @$x = 0;                       # if $a < 0
284                $x->[0] = 1 if $a == 0;        # $x == $y
285                return ($x, $rem) if wantarray; # including remainder?
286                return $x;
287            }
288            # $x >= $y, so proceed normally
289        }
290    }
291
292    # all other cases:
293
294    my $y = $c->_copy($yorg);         # always make copy to preserve
295
296    my ($car, $bar, $prd, $dd, $xi, $yi, @q, $v2, $v1, @d, $tmp, $q, $u2, $u1, $u0);
297
298    $car = $bar = $prd = 0;
299    if (($dd = int($BASE / ($y->[-1] + 1))) != 1) {
300        for $xi (@$x) {
301            $xi = $xi * $dd + $car;
302            $xi -= ($car = int($xi / $BASE)) * $BASE;
303        }
304        push(@$x, $car);
305        $car = 0;
306        for $yi (@$y) {
307            $yi = $yi * $dd + $car;
308            $yi -= ($car = int($yi / $BASE)) * $BASE;
309        }
310    } else {
311        push(@$x, 0);
312    }
313
314    # @q will accumulate the final result, $q contains the current computed
315    # part of the final result
316
317    @q = ();
318    ($v2, $v1) = @$y[-2, -1];
319    $v2 = 0 unless $v2;
320    while ($#$x > $#$y) {
321        ($u2, $u1, $u0) = @$x[-3..-1];
322        $u2 = 0 unless $u2;
323        #warn "oups v1 is 0, u0: $u0 $y->[-2] $y->[-1] l ",scalar @$y,"\n"
324        # if $v1 == 0;
325        $q = (($u0 == $v1) ? $MAX_VAL : int(($u0 * $BASE + $u1) / $v1));
326        --$q while ($v2 * $q > ($u0 * $BASE +$ u1- $q*$v1) * $BASE + $u2);
327        if ($q) {
328            ($car, $bar) = (0, 0);
329            for ($yi = 0, $xi = $#$x - $#$y - 1; $yi <= $#$y; ++$yi, ++$xi) {
330                $prd = $q * $y->[$yi] + $car;
331                $prd -= ($car = int($prd / $BASE)) * $BASE;
332                $x->[$xi] += $BASE if ($bar = (($x->[$xi] -= $prd + $bar) < 0));
333            }
334            if ($x->[-1] < $car + $bar) {
335                $car = 0;
336                --$q;
337                for ($yi = 0, $xi = $#$x - $#$y - 1; $yi <= $#$y; ++$yi, ++$xi) {
338                    $x->[$xi] -= $BASE
339                      if ($car = (($x->[$xi] += $y->[$yi] + $car) >= $BASE));
340                }
341            }
342        }
343        pop(@$x);
344        unshift(@q, $q);
345    }
346    if (wantarray) {
347        my $d = bless [], $c;
348        if ($dd != 1) {
349            $car = 0;
350            for $xi (reverse @$x) {
351                $prd = $car * $BASE + $xi;
352                $car = $prd - ($tmp = int($prd / $dd)) * $dd;
353                unshift(@$d, $tmp);
354            }
355        } else {
356            @$d = @$x;
357        }
358        @$x = @q;
359        __strip_zeros($x);
360        __strip_zeros($d);
361        return ($x, $d);
362    }
363    @$x = @q;
364    __strip_zeros($x);
365    $x;
366}
367
368# The following _mod function is an exact copy of _mod in Math::BigInt::Calc.
369
370sub _mod {
371    # if possible, use mod shortcut
372    my ($c, $x, $yo) = @_;
373
374    # slow way since $y too big
375    if (@$yo > 1) {
376        my ($xo, $rem) = $c->_div($x, $yo);
377        @$x = @$rem;
378        return $x;
379    }
380
381    my $y = $yo->[0];
382
383    # if both are single element arrays
384    if (@$x == 1) {
385        $x->[0] %= $y;
386        return $x;
387    }
388
389    # if @$x has more than one element, but @$y is a single element
390    my $b = $BASE % $y;
391    if ($b == 0) {
392        # when BASE % Y == 0 then (B * BASE) % Y == 0
393        # (B * BASE) % $y + A % Y => A % Y
394        # so need to consider only last element: O(1)
395        $x->[0] %= $y;
396    } elsif ($b == 1) {
397        # else need to go through all elements in @$x: O(N), but loop is a bit
398        # simplified
399        my $r = 0;
400        foreach (@$x) {
401            $r = ($r + $_) % $y; # not much faster, but heh...
402            #$r += $_ % $y; $r %= $y;
403        }
404        $r = 0 if $r == $y;
405        $x->[0] = $r;
406    } else {
407        # else need to go through all elements in @$x: O(N)
408        my $r = 0;
409        my $bm = 1;
410        foreach (@$x) {
411            $r = ($_ * $bm + $r) % $y;
412            $bm = ($bm * $b) % $y;
413
414            #$r += ($_ % $y) * $bm;
415            #$bm *= $b;
416            #$bm %= $y;
417            #$r %= $y;
418        }
419        $r = 0 if $r == $y;
420        $x->[0] = $r;
421    }
422    @$x = $x->[0];              # keep one element of @$x
423    return $x;
424}
425
426sub __strip_zeros {
427    # Internal normalization function that strips leading zeros from the array.
428    # Args: ref to array
429    my $x = shift;
430
431    push @$x, 0 if @$x == 0;    # div might return empty results, so fix it
432    return $x if @$x == 1;      # early out
433
434    #print "strip: cnt $cnt i $i\n";
435    # '0', '3', '4', '0', '0',
436    #  0    1    2    3    4
437    # cnt = 5, i = 4
438    # i = 4
439    # i = 3
440    # => fcnt = cnt - i (5-2 => 3, cnt => 5-1 = 4, throw away from 4th pos)
441    # >= 1: skip first part (this can be zero)
442
443    my $i = $#$x;
444    while ($i > 0) {
445        last if $x->[$i] != 0;
446        $i--;
447    }
448    $i++;
449    splice(@$x, $i) if $i < @$x;
450    $x;
451}
452
453###############################################################################
454# check routine to test internal state for corruptions
455
456sub _check {
457    # used by the test suite
458    my ($class, $x) = @_;
459
460    return "Undefined" unless defined $x;
461    return "$x is not a reference" unless ref($x);
462    return "Not an '$class'" unless ref($x) eq $class;
463
464    for (my $i = 0 ; $i <= $#$x ; ++ $i) {
465        my $e = $x -> [$i];
466
467        return "Element at index $i is undefined"
468          unless defined $e;
469
470        return "Element at index $i is a '" . ref($e) .
471          "', which is not a scalar"
472          unless ref($e) eq "";
473
474        return "Element at index $i is '$e', which does not look like an" .
475          " normal integer"
476            #unless $e =~ /^([1-9]\d*|0)\z/;
477            unless $e =~ /^\d+\z/;
478
479        return "Element at index $i is '$e', which is negative"
480          if $e < 0;
481
482        return "Element at index $i is '$e', which is not smaller than" .
483          " the base '$BASE'"
484            if $e >= $BASE;
485
486        return "Element at index $i (last element) is zero"
487          if $#$x > 0 && $i == $#$x && $e == 0;
488    }
489
490    return 0;
491}
492
493##############################################################################
494##############################################################################
495
4961;
497
498__END__
499
500=pod
501
502=head1 NAME
503
504Math::BigInt::Calc - Pure Perl module to support Math::BigInt
505
506=head1 SYNOPSIS
507
508This library provides support for big integer calculations. It is not
509intended to be used by other modules. Other modules which support the same
510API (see below) can also be used to support Math::BigInt, like
511Math::BigInt::GMP and Math::BigInt::Pari.
512
513=head1 DESCRIPTION
514
515In this library, the numbers are represented in base B = 10**N, where N is
516the largest possible value that does not cause overflow in the intermediate
517computations. The base B elements are stored in an array, with the least
518significant element stored in array element zero. There are no leading zero
519elements, except a single zero element when the number is zero.
520
521For instance, if B = 10000, the number 1234567890 is represented internally
522as [3456, 7890, 12].
523
524=head1 THE Math::BigInt API
525
526In order to allow for multiple big integer libraries, Math::BigInt was
527rewritten to use a plug-in library for core math routines. Any module which
528conforms to the API can be used by Math::BigInt by using this in your program:
529
530        use Math::BigInt lib => 'libname';
531
532'libname' is either the long name, like 'Math::BigInt::Pari', or only the short
533version, like 'Pari'.
534
535=head2 General Notes
536
537A library only needs to deal with unsigned big integers. Testing of input
538parameter validity is done by the caller, so there is no need to worry about
539underflow (e.g., in C<_sub()> and C<_dec()>) nor about division by zero (e.g.,
540in C<_div()>) or similar cases.
541
542For some methods, the first parameter can be modified. That includes the
543possibility that you return a reference to a completely different object
544instead. Although keeping the reference and just changing its contents is
545preferred over creating and returning a different reference.
546
547Return values are always objects, strings, Perl scalars, or true/false for
548comparison routines.
549
550=head2 API version 1
551
552The following methods must be defined in order to support the use by
553Math::BigInt v1.70 or later.
554
555=head3 API version
556
557=over 4
558
559=item I<api_version()>
560
561Return API version as a Perl scalar, 1 for Math::BigInt v1.70, 2 for
562Math::BigInt v1.83.
563
564=back
565
566=head3 Constructors
567
568=over 4
569
570=item I<_new(STR)>
571
572Convert a string representing an unsigned decimal number to an object
573representing the same number. The input is normalize, i.e., it matches
574C<^(0|[1-9]\d*)$>.
575
576=item I<_zero()>
577
578Return an object representing the number zero.
579
580=item I<_one()>
581
582Return an object representing the number one.
583
584=item I<_two()>
585
586Return an object representing the number two.
587
588=item I<_ten()>
589
590Return an object representing the number ten.
591
592=item I<_from_bin(STR)>
593
594Return an object given a string representing a binary number. The input has a
595'0b' prefix and matches the regular expression C<^0[bB](0|1[01]*)$>.
596
597=item I<_from_oct(STR)>
598
599Return an object given a string representing an octal number. The input has a
600'0' prefix and matches the regular expression C<^0[1-7]*$>.
601
602=item I<_from_hex(STR)>
603
604Return an object given a string representing a hexadecimal number. The input
605has a '0x' prefix and matches the regular expression
606C<^0x(0|[1-9a-fA-F][\da-fA-F]*)$>.
607
608=back
609
610=head3 Mathematical functions
611
612Each of these methods may modify the first input argument, except I<_bgcd()>,
613which shall not modify any input argument, and I<_sub()> which may modify the
614second input argument.
615
616=over 4
617
618=item I<_add(OBJ1, OBJ2)>
619
620Returns the result of adding OBJ2 to OBJ1.
621
622=item I<_mul(OBJ1, OBJ2)>
623
624Returns the result of multiplying OBJ2 and OBJ1.
625
626=item I<_div(OBJ1, OBJ2)>
627
628Returns the result of dividing OBJ1 by OBJ2 and truncating the result to an
629integer.
630
631=item I<_sub(OBJ1, OBJ2, FLAG)>
632
633=item I<_sub(OBJ1, OBJ2)>
634
635Returns the result of subtracting OBJ2 by OBJ1. If C<flag> is false or omitted,
636OBJ1 might be modified. If C<flag> is true, OBJ2 might be modified.
637
638=item I<_dec(OBJ)>
639
640Decrement OBJ by one.
641
642=item I<_inc(OBJ)>
643
644Increment OBJ by one.
645
646=item I<_mod(OBJ1, OBJ2)>
647
648Return OBJ1 modulo OBJ2, i.e., the remainder after dividing OBJ1 by OBJ2.
649
650=item I<_sqrt(OBJ)>
651
652Return the square root of the object, truncated to integer.
653
654=item I<_root(OBJ, N)>
655
656Return Nth root of the object, truncated to int. N is E<gt>= 3.
657
658=item I<_fac(OBJ)>
659
660Return factorial of object (1*2*3*4*...).
661
662=item I<_pow(OBJ1, OBJ2)>
663
664Return OBJ1 to the power of OBJ2. By convention, 0**0 = 1.
665
666=item I<_modinv(OBJ1, OBJ2)>
667
668Return modular multiplicative inverse, i.e., return OBJ3 so that
669
670    (OBJ3 * OBJ1) % OBJ2 = 1 % OBJ2
671
672The result is returned as two arguments. If the modular multiplicative
673inverse does not exist, both arguments are undefined. Otherwise, the
674arguments are a number (object) and its sign ("+" or "-").
675
676The output value, with its sign, must either be a positive value in the
677range 1,2,...,OBJ2-1 or the same value subtracted OBJ2. For instance, if the
678input arguments are objects representing the numbers 7 and 5, the method
679must either return an object representing the number 3 and a "+" sign, since
680(3*7) % 5 = 1 % 5, or an object representing the number 2 and "-" sign,
681since (-2*7) % 5 = 1 % 5.
682
683=item I<_modpow(OBJ1, OBJ2, OBJ3)>
684
685Return modular exponentiation, (OBJ1 ** OBJ2) % OBJ3.
686
687=item I<_rsft(OBJ, N, B)>
688
689Shift object N digits right in base B and return the resulting object. This is
690equivalent to performing integer division by B**N and discarding the remainder,
691except that it might be much faster, depending on how the number is represented
692internally.
693
694For instance, if the object $obj represents the hexadecimal number 0xabcde,
695then C<< $obj->_rsft(2, 16) >> returns an object representing the number 0xabc.
696The "remainer", 0xde, is discarded and not returned.
697
698=item I<_lsft(OBJ, N, B)>
699
700Shift the object N digits left in base B. This is equivalent to multiplying by
701B**N, except that it might be much faster, depending on how the number is
702represented internally.
703
704=item I<_log_int(OBJ, B)>
705
706Return integer log of OBJ to base BASE. This method has two output arguments,
707the OBJECT and a STATUS. The STATUS is Perl scalar; it is 1 if OBJ is the exact
708result, 0 if the result was truncted to give OBJ, and undef if it is unknown
709whether OBJ is the exact result.
710
711=item I<_gcd(OBJ1, OBJ2)>
712
713Return the greatest common divisor of OBJ1 and OBJ2.
714
715=back
716
717=head3 Bitwise operators
718
719Each of these methods may modify the first input argument.
720
721=over 4
722
723=item I<_and(OBJ1, OBJ2)>
724
725Return bitwise and. If necessary, the smallest number is padded with leading
726zeros.
727
728=item I<_or(OBJ1, OBJ2)>
729
730Return bitwise or. If necessary, the smallest number is padded with leading
731zeros.
732
733=item I<_xor(OBJ1, OBJ2)>
734
735Return bitwise exclusive or. If necessary, the smallest number is padded
736with leading zeros.
737
738=back
739
740=head3 Boolean operators
741
742=over 4
743
744=item I<_is_zero(OBJ)>
745
746Returns a true value if OBJ is zero, and false value otherwise.
747
748=item I<_is_one(OBJ)>
749
750Returns a true value if OBJ is one, and false value otherwise.
751
752=item I<_is_two(OBJ)>
753
754Returns a true value if OBJ is two, and false value otherwise.
755
756=item I<_is_ten(OBJ)>
757
758Returns a true value if OBJ is ten, and false value otherwise.
759
760=item I<_is_even(OBJ)>
761
762Return a true value if OBJ is an even integer, and a false value otherwise.
763
764=item I<_is_odd(OBJ)>
765
766Return a true value if OBJ is an even integer, and a false value otherwise.
767
768=item I<_acmp(OBJ1, OBJ2)>
769
770Compare OBJ1 and OBJ2 and return -1, 0, or 1, if OBJ1 is less than, equal
771to, or larger than OBJ2, respectively.
772
773=back
774
775=head3 String conversion
776
777=over 4
778
779=item I<_str(OBJ)>
780
781Return a string representing the object. The returned string should have no
782leading zeros, i.e., it should match C<^(0|[1-9]\d*)$>.
783
784=item I<_as_bin(OBJ)>
785
786Return the binary string representation of the number. The string must have a
787'0b' prefix.
788
789=item I<_as_oct(OBJ)>
790
791Return the octal string representation of the number. The string must have
792a '0x' prefix.
793
794Note: This method was required from Math::BigInt version 1.78, but the required
795API version number was not incremented, so there are older libraries that
796support API version 1, but do not support C<_as_oct()>.
797
798=item I<_as_hex(OBJ)>
799
800Return the hexadecimal string representation of the number. The string must
801have a '0x' prefix.
802
803=back
804
805=head3 Numeric conversion
806
807=over 4
808
809=item I<_num(OBJ)>
810
811Given an object, return a Perl scalar number (int/float) representing this
812number.
813
814=back
815
816=head3 Miscellaneous
817
818=over 4
819
820=item I<_copy(OBJ)>
821
822Return a true copy of the object.
823
824=item I<_len(OBJ)>
825
826Returns the number of the decimal digits in the number. The output is a
827Perl scalar.
828
829=item I<_zeros(OBJ)>
830
831Return the number of trailing decimal zeros. The output is a Perl scalar.
832
833=item I<_digit(OBJ, N)>
834
835Return the Nth digit as a Perl scalar. N is a Perl scalar, where zero refers to
836the rightmost (least significant) digit, and negative values count from the
837left (most significant digit). If $obj represents the number 123, then
838I<$obj->_digit(0)> is 3 and I<_digit(123, -1)> is 1.
839
840=item I<_check(OBJ)>
841
842Return a true value if the object is OK, and a false value otherwise. This is a
843check routine to test the internal state of the object for corruption.
844
845=back
846
847=head2 API version 2
848
849The following methods are required for an API version of 2 or greater.
850
851=head3 Constructors
852
853=over 4
854
855=item I<_1ex(N)>
856
857Return an object representing the number 10**N where N E<gt>= 0 is a Perl
858scalar.
859
860=back
861
862=head3 Mathematical functions
863
864=over 4
865
866=item I<_nok(OBJ1, OBJ2)>
867
868Return the binomial coefficient OBJ1 over OBJ1.
869
870=back
871
872=head3 Miscellaneous
873
874=over 4
875
876=item I<_alen(OBJ)>
877
878Return the approximate number of decimal digits of the object. The output is
879one Perl scalar.
880
881=back
882
883=head2 API optional methods
884
885The following methods are optional, and can be defined if the underlying lib
886has a fast way to do them. If undefined, Math::BigInt will use pure Perl (hence
887slow) fallback routines to emulate these:
888
889=head3 Signed bitwise operators.
890
891Each of these methods may modify the first input argument.
892
893=over 4
894
895=item I<_signed_or(OBJ1, OBJ2, SIGN1, SIGN2)>
896
897Return the signed bitwise or.
898
899=item I<_signed_and(OBJ1, OBJ2, SIGN1, SIGN2)>
900
901Return the signed bitwise and.
902
903=item I<_signed_xor(OBJ1, OBJ2, SIGN1, SIGN2)>
904
905Return the signed bitwise exclusive or.
906
907=back
908
909=head1 WRAP YOUR OWN
910
911If you want to port your own favourite c-lib for big numbers to the
912Math::BigInt interface, you can take any of the already existing modules as a
913rough guideline. You should really wrap up the latest Math::BigInt and
914Math::BigFloat testsuites with your module, and replace in them any of the
915following:
916
917        use Math::BigInt;
918
919by this:
920
921        use Math::BigInt lib => 'yourlib';
922
923This way you ensure that your library really works 100% within Math::BigInt.
924
925=head1 BUGS
926
927Please report any bugs or feature requests to
928C<bug-math-bigint at rt.cpan.org>, or through the web interface at
929L<https://rt.cpan.org/Ticket/Create.html?Queue=Math-BigInt>
930(requires login).
931We will be notified, and then you'll automatically be notified of progress on
932your bug as I make changes.
933
934=head1 SUPPORT
935
936You can find documentation for this module with the perldoc command.
937
938    perldoc Math::BigInt::Calc
939
940You can also look for information at:
941
942=over 4
943
944=item * RT: CPAN's request tracker
945
946L<https://rt.cpan.org/Public/Dist/Display.html?Name=Math-BigInt>
947
948=item * AnnoCPAN: Annotated CPAN documentation
949
950L<http://annocpan.org/dist/Math-BigInt>
951
952=item * CPAN Ratings
953
954L<http://cpanratings.perl.org/dist/Math-BigInt>
955
956=item * Search CPAN
957
958L<http://search.cpan.org/dist/Math-BigInt/>
959
960=item * CPAN Testers Matrix
961
962L<http://matrix.cpantesters.org/?dist=Math-BigInt>
963
964=item * The Bignum mailing list
965
966=over 4
967
968=item * Post to mailing list
969
970C<bignum at lists.scsys.co.uk>
971
972=item * View mailing list
973
974L<http://lists.scsys.co.uk/pipermail/bignum/>
975
976=item * Subscribe/Unsubscribe
977
978L<http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/bignum>
979
980=back
981
982=back
983
984=head1 LICENSE
985
986This program is free software; you may redistribute it and/or modify it under
987the same terms as Perl itself.
988
989=head1 AUTHORS
990
991=over 4
992
993=item *
994
995Original math code by Mark Biggar, rewritten by Tels L<http://bloodgate.com/>
996in late 2000.
997
998=item *
999
1000Separated from BigInt and shaped API with the help of John Peacock.
1001
1002=item *
1003
1004Fixed, speed-up, streamlined and enhanced by Tels 2001 - 2007.
1005
1006=item *
1007
1008API documentation corrected and extended by Peter John Acklam,
1009E<lt>pjacklam@online.noE<gt>
1010
1011=back
1012
1013=head1 SEE ALSO
1014
1015L<Math::BigInt>, L<Math::BigFloat>, L<Math::BigInt::GMP>,
1016L<Math::BigInt::FastCalc> and L<Math::BigInt::Pari>.
1017
1018=cut
1019