use 5.005;
use strict;
# use warnings; # dont use warnings for older Perls
use vars qw/$VERSION/;
$VERSION = '0.40';
# Package to store unsigned big integers in decimal and do math with them
# Internally the numbers are stored in an array with at least 1 element, no
# leading zero parts (except the first) and in base 1eX where X is determined
# automatically at loading time to be the maximum possible value
# todo:
# - fully remove funky $# stuff (maybe)
# USE_MUL: due to problems on certain os (os390, posix-bc) "* 1e-5" is used
# instead of "/ 1e5" at some places, (marked with USE_MUL). Other platforms
# BS2000, some Crays need USE_DIV instead.
# The BEGIN block is used to determine which of the two variants gives the
# correct result.
# Beware of things like:
# $i = $i * $y + $car; $car = int($i / $MBASE); $i = $i % $MBASE;
# This works on x86, but fails on ARM (SA1100, iPAQ) due to whoknows what
# reasons. So, use this instead (slower, but correct):
# $i = $i * $y + $car; $car = int($i / $MBASE); $i -= $MBASE * $car;
##############################################################################
# global constants, flags and accessory
# announce that we are compatible with MBI v1.70 and up
# constants for easier life
my $nan = 'NaN';
sub _base_len
{
# used only be the testsuite, set is used only by the BEGIN block below
shift;
my $b = shift;
if (defined $b)
{
# find whether we can use mul or div or none in mul()/div()
# (in last case reduce BASE_LEN_SMALL)
$BASE_LEN_SMALL = $b+1;
my $caught = 0;
while (--$BASE_LEN_SMALL > 5)
{
$caught = 0;
last if $caught != 3;
}
# BASE_LEN is used for anything else than mul()/div()
$BASE_LEN = $BASE_LEN_SMALL;
undef &_mul;
undef &_div;
# $caught & 1 != 0 => cannot use MUL
# $caught & 2 != 0 => cannot use DIV
# The parens around ($caught & 1) were important, indeed, if we would use
# & here.
{
# must USE_MUL since we cannot use DIV
*{_mul} = \&_mul_use_mul;
*{_div} = \&_div_use_mul;
}
else # 0 or 1
{
# can USE_DIV instead
*{_mul} = \&_mul_use_div;
*{_div} = \&_div_use_div;
}
}
return $BASE_LEN unless wantarray;
}
BEGIN
{
# from Daniel Pfeiffer: determine largest group of digits that is precisely
# multipliable with itself plus carry
# Test now changed to expect the proper pattern, not a result off by 1 or 2
do
{
} while ("$num" =~ /9{$e}0{$e}/); # must be a certain pattern
$e--; # last test failed, so retract one step
# the limits below brush the problems with the test above under the rug:
# the test should be able to find the proper $e automatically
# there, but we play safe)
$e = 5 if $] < 5.006; # cap, for older Perls
$e = 7 if $e > 7; # cap, for VMS, OS/390 and other 64 bit systems
# 8 fails inside random testsuite, so take 7
# determine how many digits fit into an integer and can be safely added
# together plus carry w/o causing an overflow
use integer;
############################################################################
# the next block is no longer important
## this below detects 15 on a 64 bit system, because after that it becomes
## 1e16 and not 1000000 :/ I can make it detect 18, but then I get a lot of
## test failures. Ugh! (Tomake detect 18: uncomment lines marked with *)
#my $bi = 5; # approx. 16 bit
#$num = int('9' x $bi);
## $num = 99999; # *
## while ( ($num+$num+1) eq '1' . '9' x $bi) # *
#while ( int($num+$num+1) eq '1' . '9' x $bi)
# {
# $bi++; $num = int('9' x $bi);
# # $bi++; $num *= 10; $num += 9; # *
# }
#$bi--; # back off one step
# by setting them equal, we ignore the findings and use the default
# one-size-fits-all approach from former versions
my $bi = $e; # XXX, this should work always
# find out how many bits _and, _or and _xor can take (old default = 16)
# I don't think anybody has yet 128 bit scalars, so let's play safe.
local $^W = 0; # don't warn about 'nonportable number'
# find max bits, we will not go higher than numberofbits that fit into $BASE
# to make _and etc simpler (and faster for smaller, slower for large numbers)
my $max = 16;
{
no integer;
}
my ($x,$y,$z);
do {
$AND_BITS++;
$AND_BITS --; # retreat one step
do {
$XOR_BITS++;
$XOR_BITS --; # retreat one step
do {
$OR_BITS++;
$OR_BITS --; # retreat one step
}
###############################################################################
sub _new
{
# (ref to string) return ref to num_array
# Convert a number from string format (without sign) to internal base
# 1ex format. Assumes normalized value as input.
# < BASE_LEN due len-1 above
# this leaves '00000' instead of int 0 and will be corrected after any op
}
BEGIN
{
}
sub _zero
{
# create a zero
[ 0 ];
}
sub _one
{
# create a one
[ 1 ];
}
sub _two
{
# create a two (used internally for shifting)
[ 2 ];
}
sub _ten
{
# create a 10 (used internally for shifting)
[ 10 ];
}
sub _copy
{
# make a true copy
[ @{$_[1]} ];
}
# catch and throw away
sub import { }
##############################################################################
# convert back to string and number
sub _str
{
# (ref to BINT) return num_str
# Convert number from internal base 100000 format to string format.
# internal format is always normalized (no leading zeros, "-0" => "+0")
my $ar = $_[1];
my $ret = "";
my $l = scalar @$ar; # number of parts
# handle first one different to strip leading zeros from it (there are no
# leading zero parts in internal representation)
# Interestingly, the pre-padd method uses more time
# the old grep variant takes longer (14 vs. 10 sec)
while ($l >= 0)
{
$l--;
}
$ret;
}
sub _num
{
my $x = $_[1];
return 0+$x->[0] if scalar @$x == 1; # below $BASE
my $fac = 1;
my $num = 0;
foreach (@$x)
{
}
$num;
}
##############################################################################
# actual math code
sub _add
{
# (ref to int_num_array, ref to int_num_array)
# routine to add two base 1eX numbers
# stolen from Knuth Vol 2 Algorithm A pg 231
# there are separate routines to add and sub as per Knuth pg 233
# This routine clobbers up array x, but not y.
my ($c,$x,$y) = @_;
return $x if (@$y == 1) && $y->[0] == 0; # $x + 0 => $x
if ((@$x == 1) && $x->[0] == 0) # 0 + $y => $y->copy
{
# twice as slow as $x = [ @$y ], but necc. to retain $x as ref :(
@$x = @$y; return $x;
}
# for each in Y, add Y to X and carry. If after that, something is left in
# X, foreach in X add carry to X and then return X, carry
# Trades one "$j++" for having to shift arrays
for $i (@$y)
{
$j++;
}
while ($car != 0)
{
}
$x;
}
sub _inc
{
# (ref to int_num_array, ref to int_num_array)
# Add 1 to $x, modify $x in place
my ($c,$x) = @_;
for my $i (@$x)
{
$i = 0; # overflow, next
}
push @$x,1 if ($x->[-1] == 0); # last overflowed, so extend
$x;
}
sub _dec
{
# (ref to int_num_array, ref to int_num_array)
# Sub 1 from $x, modify $x in place
my ($c,$x) = @_;
for my $i (@$x)
{
last if (($i -= 1) >= 0); # early out
$i = $MAX; # underflow, next
}
pop @$x if $x->[-1] == 0 && @$x > 1; # last underflowed (but leave 0)
$x;
}
sub _sub
{
# (ref to int_num_array, ref to int_num_array, swap)
# subtract base 1eX numbers -- stolen from Knuth Vol 2 pg 232, $x > $y
# subtract Y from X by modifying x in place
if (!$s)
{
for $i (@$sx)
{
}
# might leave leading zeros, so fix that
return __strip_zeros($sx);
}
for $i (@$sx)
{
# we can't do an early out if $x is < than $y, since we
# need to copy the high chunks from $y. Found by Bob Mathews.
#last unless defined $sy->[$j] || $car;
$j++;
}
# might leave leading zeros, so fix that
__strip_zeros($sy);
}
sub _mul_use_mul
{
# (ref to int_num_array, ref to int_num_array)
# multiply two numbers in internal representation
# modifies first arg, second need not be different from first
if (@$yv == 1)
{
# shortcut for two very short numbers (improved by Nathan Zook)
# works also if xv and yv are the same reference, and handles also $x == 0
if (@$xv == 1)
{
{
};
return $xv;
}
# $x * 0 => 0
{
@$xv = (0);
return $xv;
}
# multiply a large number a by a single element one, so speed up
foreach my $i (@$xv)
{
}
return $xv;
}
# shortcut for result $x == 0 => result = 0
# since multiplying $x with $x fails, make copy in this case
{
# slow variant
# for $yi (@$yv)
# {
# $prod = $xi * $yi + ($prod[$cty] || 0) + $car;
# $prod[$cty++] =
# $prod - ($car = int($prod * RBASE)) * $MBASE; # see USE_MUL
# }
# $prod[$cty] += $car if $car; # need really to check for 0?
# $xi = shift @prod;
# faster variant
# looping through this if $xi == 0 is silly - so optimize it away!
{
## this is actually a tad slower
## $prod = $prod[$cty]; $prod += ($car + $xi * $yi); # no ||0 here
}
}
__strip_zeros($xv);
$xv;
}
sub _mul_use_div
{
# (ref to int_num_array, ref to int_num_array)
# multiply two numbers in internal representation
# modifies first arg, second need not be different from first
if (@$yv == 1)
{
# shortcut for two small numbers, also handles $x == 0
if (@$xv == 1)
{
# shortcut for two very short numbers (improved by Nathan Zook)
# works also if xv and yv are the same reference, and handles also $x == 0
{
$xv->[0] =
};
return $xv;
}
# $x * 0 => 0
{
@$xv = (0);
return $xv;
}
# multiply a large number a by a single element one, so speed up
foreach my $i (@$xv)
{
}
return $xv;
}
# shortcut for result $x == 0 => result = 0
# since multiplying $x with $x fails, make copy in this case
{
# looping through this if $xi == 0 is silly - so optimize it away!
{
}
}
__strip_zeros($xv);
$xv;
}
sub _div_use_mul
{
# ref to array, ref to array, modify first array and return remainder if
# in list context
# see comments in _div_use_div() for more explanations
my ($c,$x,$yorg) = @_;
# the general div algorithmn here is about O(N*N) and thus quite slow, so
# we first check for some special cases and use shortcuts to handle them.
# This works, because we store the numbers in a chunked format where each
# element contains 5..7 digits (depending on system).
# if both numbers have only one element:
{
# shortcut, $yorg and $x are two small numbers
if (wantarray)
{
return ($x,$r);
}
else
{
return $x;
}
}
# if x has more than one, but y has only one element:
if (@$yorg == 1)
{
my $rem;
# shortcut, $y is < $BASE
my $j = scalar @$x; my $r = 0;
my $y = $yorg->[0]; my $b;
while ($j-- > 0)
{
$b = $r * $MBASE + $x->[$j];
$x->[$j] = int($b/$y);
$r = $b % $y;
}
pop @$x if @$x > 1 && $x->[-1] == 0; # splice up a leading zero
return ($x,$rem) if wantarray;
return $x;
}
# now x and y have more than one element
# check whether y has more elements than x, if yet, the result will be 0
if (@$yorg > @$x)
{
my $rem;
$rem = [@$x] if wantarray; # make copy
splice (@$x,1); # keep ref to original array
$x->[0] = 0; # set to 0
return ($x,$rem) if wantarray; # including remainder?
return $x; # only x, which is [0] now
}
# check whether the numbers have the same number of elements, in that case
# the result will fit into one element and can be computed efficiently
if (@$yorg == @$x)
{
my $rem;
# if $yorg has more digits than $x (it's leading element is longer than
# the one from $x), the result will also be 0:
{
$rem = [@$x] if wantarray; # make copy
splice (@$x,1); # keep ref to org array
$x->[0] = 0; # set to 0
return ($x,$rem) if wantarray; # including remainder?
return $x;
}
# now calculate $x / $yorg
{
# same length, so make full compare, and if equal, return 1
# hm, same lengths, but same contents? So we need to check all parts:
my $a = 0; my $j = scalar @$x - 1;
# manual way (abort if unequal, good for early ne)
while ($j >= 0)
{
last if ($a = $x->[$j] - $yorg->[$j]); $j--;
}
# $a contains the result of the compare between X and Y
# a < 0: x < y, a == 0 => x == y, a > 0: x > y
if ($a <= 0)
{
if (wantarray)
{
}
splice(@$x,1); # keep single element
$x->[0] = 0; # if $a < 0
if ($a == 0)
{
# $x == $y
$x->[0] = 1;
}
return ($x,$rem) if wantarray;
return $x;
}
# $x >= $y, proceed normally
}
}
# all other cases:
my $y = [ @$yorg ]; # always make copy to preserve
{
for $xi (@$x)
{
}
for $yi (@$y)
{
}
}
else
{
push(@$x, 0);
}
while ($#$x > $#$y)
{
#warn "oups v1 is 0, u0: $u0 $y->[-2] $y->[-1] l ",scalar @$y,"\n"
# if $v1 == 0;
if ($q)
{
{
}
{
$car = 0; --$q;
{
}
}
}
pop(@$x);
unshift(@q, $q);
}
if (wantarray)
{
@d = ();
if ($dd != 1)
{
$car = 0;
for $xi (reverse @$x)
{
unshift(@d, $tmp);
}
}
else
{
@d = @$x;
}
@$x = @q;
my $d = \@d;
__strip_zeros($x);
__strip_zeros($d);
return ($x,$d);
}
@$x = @q;
__strip_zeros($x);
$x;
}
sub _div_use_div
{
# ref to array, ref to array, modify first array and return remainder if
# in list context
my ($c,$x,$yorg) = @_;
# the general div algorithmn here is about O(N*N) and thus quite slow, so
# we first check for some special cases and use shortcuts to handle them.
# This works, because we store the numbers in a chunked format where each
# element contains 5..7 digits (depending on system).
# if both numbers have only one element:
{
# shortcut, $yorg and $x are two small numbers
if (wantarray)
{
return ($x,$r);
}
else
{
return $x;
}
}
# if x has more than one, but y has only one element:
if (@$yorg == 1)
{
my $rem;
# shortcut, $y is < $BASE
my $j = scalar @$x; my $r = 0;
my $y = $yorg->[0]; my $b;
while ($j-- > 0)
{
$b = $r * $MBASE + $x->[$j];
$x->[$j] = int($b/$y);
$r = $b % $y;
}
pop @$x if @$x > 1 && $x->[-1] == 0; # splice up a leading zero
return ($x,$rem) if wantarray;
return $x;
}
# now x and y have more than one element
# check whether y has more elements than x, if yet, the result will be 0
if (@$yorg > @$x)
{
my $rem;
$rem = [@$x] if wantarray; # make copy
splice (@$x,1); # keep ref to original array
$x->[0] = 0; # set to 0
return ($x,$rem) if wantarray; # including remainder?
return $x; # only x, which is [0] now
}
# check whether the numbers have the same number of elements, in that case
# the result will fit into one element and can be computed efficiently
if (@$yorg == @$x)
{
my $rem;
# if $yorg has more digits than $x (it's leading element is longer than
# the one from $x), the result will also be 0:
{
$rem = [@$x] if wantarray; # make copy
splice (@$x,1); # keep ref to org array
$x->[0] = 0; # set to 0
return ($x,$rem) if wantarray; # including remainder?
return $x;
}
# now calculate $x / $yorg
{
# same length, so make full compare, and if equal, return 1
# hm, same lengths, but same contents? So we need to check all parts:
my $a = 0; my $j = scalar @$x - 1;
# manual way (abort if unequal, good for early ne)
while ($j >= 0)
{
last if ($a = $x->[$j] - $yorg->[$j]); $j--;
}
# $a contains the result of the compare between X and Y
# a < 0: x < y, a == 0 => x == y, a > 0: x > y
if ($a <= 0)
{
if (wantarray)
{
}
splice(@$x,1); # keep single element
$x->[0] = 0; # if $a < 0
if ($a == 0)
{
# $x == $y
$x->[0] = 1;
}
return ($x,$rem) if wantarray;
return $x;
}
# $x >= $y, so proceed normally
}
}
# all other cases:
my $y = [ @$yorg ]; # always make copy to preserve
{
for $xi (@$x)
{
}
for $yi (@$y)
{
}
}
else
{
push(@$x, 0);
}
# @q will accumulate the final result, $q contains the current computed
# part of the final result
while ($#$x > $#$y)
{
#warn "oups v1 is 0, u0: $u0 $y->[-2] $y->[-1] l ",scalar @$y,"\n"
# if $v1 == 0;
if ($q)
{
{
}
{
$car = 0; --$q;
{
}
}
}
pop(@$x); unshift(@q, $q);
}
if (wantarray)
{
@d = ();
if ($dd != 1)
{
$car = 0;
for $xi (reverse @$x)
{
unshift(@d, $tmp);
}
}
else
{
@d = @$x;
}
@$x = @q;
my $d = \@d;
__strip_zeros($x);
__strip_zeros($d);
return ($x,$d);
}
@$x = @q;
__strip_zeros($x);
$x;
}
##############################################################################
# testing
sub _acmp
{
# internal absolute post-normalized compare (ignore signs)
# ref to array, ref to array, return <0, 0, >0
# arrays must have at least one entry; this is not checked for
# shortcut for short numbers
# fast comp based on number of array elements (aka pseudo-length)
# or length of first element if same number of elements (aka difference 0)
||
# need int() here because sometimes the last element is '00018' vs '18'
# manual way (abort if unequal, good for early ne)
my $a; my $j = scalar @$cx;
while (--$j >= 0)
{
}
$a <=> 0;
}
sub _len
{
# compute number of digits
# '5' in this place, thus causing length() to report wrong length
my $cx = $_[1];
}
sub _digit
{
# return the nth digit, negative values count backward
# zero is rightmost, so _digit(123,0) will give 3
my ($c,$x,$n) = @_;
$n = abs($n); # if negative was too big
}
sub _zeros
{
# return amount of trailing zeros in decimal
# check each array elem in _m for having 0 at end as long as elem == 0
# Upon finding a elem != 0, stop
my $x = $_[1];
return 0 if scalar @$x == 1 && $x->[0] == 0;
foreach my $e (@$x)
{
if ($e != 0)
{
last; # early out
}
$zeros ++; # real else branch: 50% slower!
}
$zeros;
}
##############################################################################
# _is_* routines
sub _is_zero
{
# return true if arg is zero
(((scalar @{$_[1]} == 1) && ($_[1]->[0] == 0))) <=> 0;
}
sub _is_even
{
# return true if arg is even
(!($_[1]->[0] & 1)) <=> 0;
}
sub _is_odd
{
# return true if arg is even
(($_[1]->[0] & 1)) <=> 0;
}
sub _is_one
{
# return true if arg is one
(scalar @{$_[1]} == 1) && ($_[1]->[0] == 1) <=> 0;
}
sub _is_two
{
# return true if arg is two
(scalar @{$_[1]} == 1) && ($_[1]->[0] == 2) <=> 0;
}
sub _is_ten
{
# return true if arg is ten
(scalar @{$_[1]} == 1) && ($_[1]->[0] == 10) <=> 0;
}
sub __strip_zeros
{
# internal normalization function that strips leading zeros from the array
# args: ref to array
my $s = shift;
my $cnt = scalar @$s; # get count of parts
my $i = $cnt-1;
push @$s,0 if $i < 0; # div might return empty results, so fix it
return $s if @$s == 1; # early out
#print "strip: cnt $cnt i $i\n";
# '0', '3', '4', '0', '0',
# 0 1 2 3 4
# cnt = 5, i = 4
# i = 4
# i = 3
# => fcnt = cnt - i (5-2 => 3, cnt => 5-1 = 4, throw away from 4th pos)
# >= 1: skip first part (this can be zero)
while ($i > 0) { last if $s->[$i] != 0; $i--; }
$i++; splice @$s,$i if ($i < $cnt); # $i cant be 0
$s;
}
###############################################################################
# check routine to test internal state for corruptions
sub _check
{
# used by the test suite
my $x = $_[1];
return "$x is not a reference" if !ref($x);
# are all parts are valid?
my $i = 0; my $j = scalar @$x; my ($e,$try);
while ($i < $j)
{
$e = $x->[$i]; $e = 'undef' unless defined $e;
last if $e !~ /^[+]?[0-9]+$/;
last if "$e" !~ /^[+]?[0-9]+$/;
last if '' . "$e" !~ /^[+]?[0-9]+$/;
last if $e <0 || $e >= $BASE;
#$try = '=~ /^00+/; '."($x, $e)";
#last if $e =~ /^00+/;
$i++;
}
return "Illegal part '$e' at pos $i (tested: $try)" if $i < $j;
0;
}
###############################################################################
sub _mod
{
# if possible, use mod shortcut
my ($c,$x,$yo) = @_;
# slow way since $y to big
if (scalar @$yo > 1)
{
return $rem;
}
my $y = $yo->[0];
# both are single element arrays
if (scalar @$x == 1)
{
$x->[0] %= $y;
return $x;
}
# @y is a single element, but @x has more than one element
my $b = $BASE % $y;
if ($b == 0)
{
# when BASE % Y == 0 then (B * BASE) % Y == 0
# (B * BASE) % $y + A % Y => A % Y
# so need to consider only last element: O(1)
$x->[0] %= $y;
}
elsif ($b == 1)
{
# else need to go through all elements: O(N), but loop is a bit simplified
my $r = 0;
foreach (@$x)
{
$r = ($r + $_) % $y; # not much faster, but heh...
#$r += $_ % $y; $r %= $y;
}
$r = 0 if $r == $y;
$x->[0] = $r;
}
else
{
# else need to go through all elements: O(N)
foreach (@$x)
{
$r = ($_ * $bm + $r) % $y;
#$r += ($_ % $y) * $bm;
#$bm *= $b;
#$bm %= $y;
#$r %= $y;
}
$r = 0 if $r == $y;
$x->[0] = $r;
}
splice (@$x,1); # keep one element of $x
$x;
}
##############################################################################
# shifts
sub _rsft
{
my ($c,$x,$y,$n) = @_;
if ($n != 10)
{
}
# shortcut (faster) for shifting by 10)
# multiples of $BASE_LEN
{
# 12345 67890 shifted right by more than 10 digits => 0
splice (@$x,1); # leave only one element
$x->[0] = 0; # set to zero
return $x;
}
if ($rem == 0)
{
}
else
{
$x->[scalar @$x] = 0; # avoid || 0 test inside loop
{
$src++;
$dst++;
}
pop @$x if $x->[-1] == 0 && @$x > 1; # kill last element if 0
} # else rem == 0
$x;
}
sub _lsft
{
my ($c,$x,$y,$n) = @_;
if ($n != 10)
{
}
# shortcut (faster) for shifting by 10) since we are in base 10eX
# multiples of $BASE_LEN:
my $src = scalar @$x; # source
my $vd; # further speedup
my $z = '0' x $BASE_LEN;
while ($src >= 0)
{
}
# set lowest parts to 0
# fix spurios last zero element
splice @$x,-1 if $x->[-1] == 0;
$x;
}
sub _pow
{
# power of $x to $y
# ref to array, ref to array, return ref to array
{
return $cx;
}
{
return $cx;
}
{
return $cx;
}
while (--$len > 0)
{
}
$cx;
}
sub _fac
{
# factorial of $x
# ref to array, return ref to array
my ($c,$cx) = @_;
{
return $cx;
}
# go forward until $base is exceeded
# limit is either $x steps (steps == 100 means a result always too high) or
# $base.
{
}
{
# completely done, so keep reference to $x and return
$cx->[0] = $r;
return $cx;
}
# now we must do the left over steps
my $n; # steps still to do
if (scalar @$cx == 1)
{
$n = $cx->[0];
}
else
{
}
my $zero_elements = 0;
# do left-over steps fit into a scalar?
if (ref $n eq 'ARRAY')
{
# No, so use slower inc() & cmp()
{
# as soon as the last element of $cx is 0, we split it up and remember
# how many zeors we got so far. The reason is that n! will accumulate
# zeros at the end rather fast.
{
$zero_elements ++; shift @$cx;
}
}
}
else
{
# Yes, so we can speed it up slightly
while ($step <= $n)
{
# When the last element of $cx is 0, we split it up and remember
# how many we got so far. The reason is that n! will accumulate
# zeros at the end rather fast.
{
$zero_elements ++; shift @$cx;
}
}
}
# multiply in the zeros again
while ($zero_elements-- > 0)
{
unshift @$cx, 0;
}
$cx; # return result
}
#############################################################################
sub _log_int
{
# calculate integer log of $x to base $base
# ref to array, ref to array - return ref to array
my ($c,$x,$base) = @_;
# X == 0 => NaN
return if (scalar @$x == 1 && $x->[0] == 0);
# BASE 0 or 1 => NaN
if ($cmp == 0)
{
splice (@$x,1); $x->[0] = 1;
return ($x,1)
}
# X < BASE
if ($cmp < 0)
{
splice (@$x,1); $x->[0] = 0;
return ($x,undef);
}
# this trial multiplication is very fast, even for large counts (like for
# 2 ** 1024, since this still requires only 1024 very fast steps
# (multiplication of a large number by a very small number is very fast))
splice(@$x,1); $x->[0] = 1; # keep ref to $x
# XXX TODO this only works if $base has only one element
if (scalar @$base == 1)
{
# compute int ( length_in_base_10(X) / ( log(base) / log(10) ) )
$x->[0] = $res;
return ($x,1) if $a == 0;
# we now know that $res is too small
if ($res < 0)
{
}
else
{
# or too big
}
# did we now get the right result?
return ($x,1) if $a == 0; # yes, exactly
# still too big
if ($a > 0)
{
}
}
# simple loop that increments $x by two in each step, possible overstepping
# the real result by one
my $a;
{
}
my $exact = 1;
if ($a > 0)
{
# overstepped the result
_dec($c, $x);
if ($a > 0)
{
_dec($c, $x);
}
}
($x,$exact); # return result
}
# for debugging:
my $steps = 0;
sub _sqrt
{
# square-root of $x in place
# Compute a guess of the result (by rule of thumb), then improve it via
# Newton's method.
my ($c,$x) = @_;
if (scalar @$x == 1)
{
# fit's into one Perl scalar, so result can be computed directly
$x->[0] = int(sqrt($x->[0]));
return $x;
}
my $y = _copy($c,$x);
# hopefully _len/2 is < $BASE, the -1 is to always undershot the guess
# since our guess will "grow"
my $elems = scalar @$x - 1;
# not enough digits, but could have more?
{
# right-align with zero pad
print "$lastelem => " if DEBUG;
# former odd => make odd again, or former even to even again
print "$lastelem\n" if DEBUG;
}
# construct $x (instead of _lsft($c,$x,$l,10)
my $r = $l % $BASE_LEN; # 10000 00000 00000 00000 ($BASE_LEN=5)
$l = int($l / $BASE_LEN);
print "l = $l " if DEBUG;
splice @$x,$l; # keep ref($x), but modify it
# we make the first part of the guess not '1000...0' but int(sqrt($lastelem))
# that gives us:
# 14400 00000 => sqrt(14400) => guess first digits to be 120
# 144000 000000 => sqrt(144000) => guess 379
print "$lastelem (elems $elems) => " if DEBUG;
my $g = sqrt($lastelem); $g =~ s/\.//; # 2.345 => 2345
# padd with zeros if result is too short
$x->[$l--] = int(substr($g . '0' x $r,0,$r+1));
# If @$x > 1, we could compute the second elem of the guess, too, to create
# an even better guess. Not implemented yet. Does it improve performance?
$x->[$l--] = 0 while ($l >= 0); # all other digits of guess are zero
{
}
print "\nsteps in sqrt: $steps, " if DEBUG;
$x;
}
sub _root
{
# take n'th root of $x in place (n >= 3)
my ($c,$x,$n) = @_;
if (scalar @$x == 1)
{
if (scalar @$n > 1)
{
# result will always be smaller than 2 so trunc to 1 at once
$x->[0] = 1;
}
else
{
# fit's into one Perl scalar, so result can be computed directly
# cannot use int() here, because it rounds wrongly (try
# (81 ** 3) ** (1/3) to see what I mean)
#$x->[0] = int( $x->[0] ** (1 / $n->[0]) );
# round to 8 digits, then truncate result to integer
$x->[0] = int ( sprintf ("%.8f", $x->[0] ** (1 / $n->[0]) ) );
}
return $x;
}
# we know now that X is more than one element long
# if $n is a power of two, we can repeatedly take sqrt($X) and find the
# proper result, because sqrt(sqrt($x)) == root($x,4)
my $b = _as_bin($c,$n);
{
unshift (@$x, 0); # add one element, together with one
# more below in the loop this makes 2
while ($cnt-- > 0)
{
# 'inflate' $X by adding one element, basically computing
# $x * $BASE * $BASE. This gives us more $BASE_LEN digits for result
# since len(sqrt($X)) approx == len($x) / 2.
unshift (@$x, 0);
# calculate sqrt($x), $x is now one element to big, again. In the next
# round we make that two, again.
_sqrt($c,$x);
}
# $x is now one element to big, so truncate result by removing it
splice (@$x,0,1);
}
else
{
# trial computation by starting with 2,4,8,16 etc until we overstep
my $step;
# while still to do more than X steps
do
{
{
}
# hit exactly?
{
@$x = @$trial; # make copy while preserving ref to $x
return $x;
}
# overstepped, so go back on step
# reset step to 2
# add two, because $trial cannot be exactly the result (otherwise we would
# alrady have found it)
# and now add more and more (2,4,6,8,10 etc)
{
}
# hit not exactly? (overstepped)
{
}
# hit not exactly? (overstepped)
# 80 too small, 81 slightly too big, 82 too big
{
}
@$x = @$trial; # make copy while preserving ref to $x
return $x;
}
$x;
}
##############################################################################
# binary stuff
sub _and
{
my ($c,$x,$y) = @_;
# the shortcut makes equal, large numbers _really_ fast, and makes only a
# very small performance drop for small numbers (e.g. something with less
# than 32 bit) Since we optimize for large numbers, this is enabled.
my $x1 = $x;
$x = _zero();
use integer;
{
# make ints() from $xr, $yr
# this is when the AND_BITS are greater than $BASE and is slower for
# small (<256 bits) numbers, but faster for large numbers. Disabled
# due to KISS principle
# $b = 1; $xrr = 0; foreach (@$xr) { $xrr += $_ * $b; $b *= $BASE; }
# $b = 1; $yrr = 0; foreach (@$yr) { $yrr += $_ * $b; $b *= $BASE; }
# _add($c,$x, _mul($c, _new( $c, ($xrr & $yrr) ), $m) );
# 0+ due to '&' doesn't work in strings
}
$x;
}
sub _xor
{
my ($c,$x,$y) = @_;
my $x1 = $x;
$x = _zero();
use integer;
{
# make ints() from $xr, $yr (see _and())
#$b = 1; $xrr = 0; foreach (@$xr) { $xrr += $_ * $b; $b *= $BASE; }
#$b = 1; $yrr = 0; foreach (@$yr) { $yrr += $_ * $b; $b *= $BASE; }
#_add($c,$x, _mul($c, _new( $c, ($xrr ^ $yrr) ), $m) );
# 0+ due to '^' doesn't work in strings
}
# the loop stops when the shorter of the two numbers is exhausted
# the remainder of the longer one will survive bit-by-bit, so we simple
# multiply-add it in
$x;
}
sub _or
{
my ($c,$x,$y) = @_;
my $x1 = $x;
$x = _zero();
use integer;
{
# make ints() from $xr, $yr (see _and())
# $b = 1; $xrr = 0; foreach (@$xr) { $xrr += $_ * $b; $b *= $BASE; }
# $b = 1; $yrr = 0; foreach (@$yr) { $yrr += $_ * $b; $b *= $BASE; }
# _add($c,$x, _mul($c, _new( $c, ($xrr | $yrr) ), $m) );
# 0+ due to '|' doesn't work in strings
}
# the loop stops when the shorter of the two numbers is exhausted
# the remainder of the longer one will survive bit-by-bit, so we simple
# multiply-add it in
$x;
}
sub _as_hex
{
# convert a decimal number to hex (ref to array, return ref to string)
my ($c,$x) = @_;
# fit's into one element (handle also 0x0 case)
if (@$x == 1)
{
my $t = sprintf("0x%x",$x->[0]);
return $t;
}
my $es = '';
if ($] >= 5.006)
{
}
else
{
}
# while (! _is_zero($c,$x1))
{
}
$es;
}
sub _as_bin
{
# convert a decimal number to bin (ref to array, return ref to string)
my ($c,$x) = @_;
# fit's into one element (and Perl recent enough), handle also 0b0 case
# handle zero case for older Perls
if ($] <= 5.005 && @$x == 1 && $x->[0] == 0)
{
my $t = '0b0'; return $t;
}
if (@$x == 1 && $] >= 5.006)
{
my $t = sprintf("0b%b",$x->[0]);
return $t;
}
my $es = '';
if ($] >= 5.006)
{
}
else
{
}
# while (! _is_zero($c,$x1))
{
# $es .= unpack($b,$xr->[0]);
}
$es;
}
sub _from_hex
{
# convert a hex number to decimal (ref to string, return ref to array)
my ($c,$hs) = @_;
my $m = [ 0x10000 ]; # 16 bit at a time
my $x = _zero();
my $val; my $i = -4;
while ($len >= 0)
{
$i -= 4; $len --;
}
$x;
}
sub _from_bin
{
# convert a hex number to decimal (ref to string, return ref to array)
my ($c,$bs) = @_;
# instead of converting X (8) bit at a time, it is faster to "convert" the
# number to hex, and then call _from_hex.
my $l = length($hs); # bits
$c->_from_hex('0x'.$h);
}
##############################################################################
# special modulus functions
sub _modinv
{
# modular inverse
my ($c,$x,$y) = @_;
# Euclid's Algorithm for bgcd(), only that we calc bgcd() ($a) and the
# result ($u) at the same time. See comments in BigInt for why this works.
my $q;
($a, $q, $b) = ($b, _div($c,$a,$b)); # step 1
my $sign = 1;
while (!_is_zero($c,$b))
{
my $t = _add($c, # step 2:
$u ); # + u
$u = $u1; # u = u1, u1 = t
$u1 = $t;
($a, $q, $b) = ($b, _div($c,$a,$b)); # step 1
}
# if the gcd is not 1, then return NaN
return (undef,undef) unless _is_one($c,$a);
}
sub _modpow
{
# modulus of power ($x ** $y) % $z
# in the trivial case,
{
return $num;
}
{
return $num;
}
# $num = _mod($c,$num,$mod); # this does not make it faster
while (--$len >= 0)
{
{
}
}
@$num = @$t;
$num;
}
sub _gcd
{
# greatest common divisor
my ($c,$x,$y) = @_;
while (! _is_zero($c,$y))
{
my $t = _copy($c,$y);
$y = _mod($c, $x, $y);
$x = $t;
}
$x;
}
##############################################################################
##############################################################################
1;
=head1 NAME
Math::BigInt::Calc - Pure Perl module to support Math::BigInt
=head1 SYNOPSIS
Provides support for big integer calculations. Not intended to be used by other
modules. Other modules which sport the same functions can also be used to support
Math::BigInt, like Math::BigInt::GMP or Math::BigInt::Pari.
=head1 DESCRIPTION
In order to allow for multiple big integer libraries, Math::BigInt was
rewritten to use library modules for core math routines. Any module which
follows the same API as this can be used instead by using the following:
use Math::BigInt lib => 'libname';
'libname' is either the long name ('Math::BigInt::Pari'), or only the short
version like 'Pari'.
=head1 STORAGE
=head1 METHODS
The following functions MUST be defined in order to support the use by
Math::BigInt v1.70 or later:
api_version() return API version, minimum 1 for v1.70
_new(string) return ref to new object from ref to decimal string
_zero() return a new object with value 0
_one() return a new object with value 1
_two() return a new object with value 2
_ten() return a new object with value 10
_str(obj) return ref to a string representing the object
NOTE: because of Perl numeric notation defaults,
the _num'ified obj may lose accuracy due to
machine-dependend floating point size limitations
_add(obj,obj) Simple addition of two objects
_mul(obj,obj) Multiplication of two objects
_div(obj,obj) Division of the 1st object by the 2nd
In list context, returns (result,remainder).
NOTE: this is integer math, so no
fractional part will be returned.
The second operand will be not be 0, so no need to
check for that.
_sub(obj,obj) Simple subtraction of 1 object from another
a third, optional parameter indicates that the params
are swapped. In this case, the first param needs to
be preserved, while you can destroy the second.
sub (x,y,1) => return x - y and keep x intact!
_dec(obj) decrement object by one (input is garant. to be > 0)
_inc(obj) increment object by one
_acmp(obj,obj) <=> operator for objects (return -1, 0 or 1)
_len(obj) returns count of the decimal digits of the object
_digit(obj,n) returns the n'th decimal digit of object
_is_one(obj) return true if argument is 1
_is_two(obj) return true if argument is 2
_is_ten(obj) return true if argument is 10
_is_zero(obj) return true if argument is 0
_is_even(obj) return true if argument is even (0,2,4,6..)
_is_odd(obj) return true if argument is odd (1,3,5,7..)
_copy return a ref to a true copy of the object
_check(obj) check whether internal representation is still intact
return 0 for ok, otherwise error message as string
_from_hex(str) return ref to new object from ref to hexadecimal string
_from_bin(str) return ref to new object from ref to binary string
_as_hex(str) return string containing the value as
unsigned hex string, with the '0x' prepended.
Leading zeros must be stripped.
_as_bin(str) Like as_hex, only as binary string containing only
zeros and ones. Leading zeros must be stripped and a
'0b' must be prepended.
_rsft(obj,N,B) shift object in base B by N 'digits' right
_lsft(obj,N,B) shift object in base B by N 'digits' left
_xor(obj1,obj2) XOR (bit-wise) object 1 with object 2
Note: XOR, AND and OR pad with zeros if size mismatches
_and(obj1,obj2) AND (bit-wise) object 1 with object 2
_or(obj1,obj2) OR (bit-wise) object 1 with object 2
_mod(obj,obj) Return remainder of div of the 1st by the 2nd object
_sqrt(obj) return the square root of object (truncated to int)
_root(obj) return the n'th (n >= 3) root of obj (truncated to int)
_fac(obj) return factorial of object 1 (1*2*3*4..)
_pow(obj,obj) return object 1 to the power of object 2
return undef for NaN
_zeros(obj) return number of trailing decimal zeros
_modinv return inverse modulus
_modpow return modulus of power ($x ** $y) % $z
_log_int(X,N) calculate integer log() of X in base N
X >= 0, N >= 0 (return undef for NaN)
returns (RESULT, EXACT) where EXACT is:
1 : result is exactly RESULT
0 : result was truncated to RESULT
undef : unknown whether result is exactly RESULT
_gcd(obj,obj) return Greatest Common Divisor of two objects
The following functions are optional, and can be defined if the underlying lib
has a fast way to do them. If undefined, Math::BigInt will use pure Perl (hence
slow) fallback routines to emulate these:
_signed_or
_signed_and
_signed_xor
Input strings come in as unsigned but with prefix (i.e. as '123', '0xabc'
or '0b1101').
So the library needs only to deal with unsigned big integers. Testing of input
parameter validity is done by the caller, so you need not worry about
underflow (f.i. in C<_sub()>, C<_dec()>) nor about division by zero or similar
cases.
The first parameter can be modified, that includes the possibility that you
return a reference to a completely different object instead. Although keeping
the reference and just changing it's contents is prefered over creating and
returning a different reference.
comparisation routines.
=head1 WRAP YOUR OWN
If you want to port your own favourite c-lib for big numbers to the
Math::BigInt interface, you can take any of the already existing modules as
a rough guideline. You should really wrap up the latest BigInt and BigFloat
testsuites with your module, and replace in them any of the following:
use Math::BigInt;
by this:
use Math::BigInt lib => 'yourlib';
This way you ensure that your library really works 100% within Math::BigInt.
=head1 LICENSE
the same terms as Perl itself.
=head1 AUTHORS
Original math code by Mark Biggar, rewritten by Tels L<http://bloodgate.com/>
in late 2000.
Seperated from BigInt and shaped API with the help of John Peacock.
Fixed, sped-up and enhanced by Tels http://bloodgate.com 2001-2003.
Further streamlining (api_version 1) by Tels 2004.
=head1 SEE ALSO
L<Math::BigInt>, L<Math::BigFloat>, L<Math::BigInt::BitVect>,
L<Math::BigInt::GMP>, L<Math::BigInt::FastCalc> and L<Math::BigInt::Pari>.
=cut