home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / PERL4036.ZIP / lib / bigint.pl < prev    next >
Perl Script  |  1993-02-08  |  8KB  |  272 lines

  1. package bigint;
  2.  
  3. # arbitrary size integer math package
  4. #
  5. # by Mark Biggar
  6. #
  7. # Canonical Big integer value are strings of the form
  8. #       /^[+-]\d+$/ with leading zeros suppressed
  9. # Input values to these routines may be strings of the form
  10. #       /^\s*[+-]?[\d\s]+$/.
  11. # Examples:
  12. #   '+0'                            canonical zero value
  13. #   '   -123 123 123'               canonical value '-123123123'
  14. #   '1 23 456 7890'                 canonical value '+1234567890'
  15. # Output values always always in canonical form
  16. #
  17. # Actual math is done in an internal format consisting of an array
  18. #   whose first element is the sign (/^[+-]$/) and whose remaining 
  19. #   elements are base 100000 digits with the least significant digit first.
  20. # The string 'NaN' is used to represent the result when input arguments 
  21. #   are not numbers, as well as the result of dividing by zero
  22. #
  23. # routines provided are:
  24. #
  25. #   bneg(BINT) return BINT              negation
  26. #   babs(BINT) return BINT              absolute value
  27. #   bcmp(BINT,BINT) return CODE         compare numbers (undef,<0,=0,>0)
  28. #   badd(BINT,BINT) return BINT         addition
  29. #   bsub(BINT,BINT) return BINT         subtraction
  30. #   bmul(BINT,BINT) return BINT         multiplication
  31. #   bdiv(BINT,BINT) return (BINT,BINT)  division (quo,rem) just quo if scalar
  32. #   bmod(BINT,BINT) return BINT         modulus
  33. #   bgcd(BINT,BINT) return BINT         greatest common divisor
  34. #   bnorm(BINT) return BINT             normalization
  35. #
  36.  
  37. # normalize string form of number.   Strip leading zeros.  Strip any
  38. #   white space and add a sign, if missing.
  39. # Strings that are not numbers result the value 'NaN'.
  40. sub main'bnorm { #(num_str) return num_str
  41.     local($_) = @_;
  42.     s/\s+//g;                           # strip white space
  43.     if (s/^([+-]?)0*(\d+)$/$1$2/) {     # test if number
  44.     substr($_,0,0) = '+' unless $1; # Add missing sign
  45.     s/^-0/+0/;
  46.     $_;
  47.     } else {
  48.     'NaN';
  49.     }
  50. }
  51.  
  52. # Convert a number from string format to internal base 100000 format.
  53. #   Assumes normalized value as input.
  54. sub internal { #(num_str) return int_num_array
  55.     local($d) = @_;
  56.     ($is,$il) = (substr($d,0,1),length($d)-2);
  57.     substr($d,0,1) = '';
  58.     ($is, reverse(unpack("a" . ($il%5+1) . ("a5" x ($il/5)), $d)));
  59. }
  60.  
  61. # Convert a number from internal base 100000 format to string format.
  62. #   This routine scribbles all over input array.
  63. sub external { #(int_num_array) return num_str
  64.     $es = shift;
  65.     grep($_ > 9999 || ($_ = substr('0000'.$_,-5)), @_);   # zero pad
  66.     &'bnorm(join('', $es, reverse(@_)));    # reverse concat and normalize
  67. }
  68.  
  69. # Negate input value.
  70. sub main'bneg { #(num_str) return num_str
  71.     local($_) = &'bnorm(@_);
  72.     vec($_,0,8) ^= ord('+') ^ ord('-') unless $_ eq '+0';
  73.     s/^H/N/;
  74.     $_;
  75. }
  76.  
  77. # Returns the absolute value of the input.
  78. sub main'babs { #(num_str) return num_str
  79.     &abs(&'bnorm(@_));
  80. }
  81.  
  82. sub abs { # post-normalized abs for internal use
  83.     local($_) = @_;
  84.     s/^-/+/;
  85.     $_;
  86. }
  87.  
  88. # Compares 2 values.  Returns one of undef, <0, =0, >0. (suitable for sort)
  89. sub main'bcmp { #(num_str, num_str) return cond_code
  90.     local($x,$y) = (&'bnorm($_[0]),&'bnorm($_[1]));
  91.     if ($x eq 'NaN') {
  92.     undef;
  93.     } elsif ($y eq 'NaN') {
  94.     undef;
  95.     } else {
  96.     &cmp($x,$y);
  97.     }
  98. }
  99.  
  100. sub cmp { # post-normalized compare for internal use
  101.     local($cx, $cy) = @_;
  102.     $cx cmp $cy
  103.     &&
  104.     (
  105.     ord($cy) <=> ord($cx)
  106.     ||
  107.     ($cx cmp ',') * (length($cy) <=> length($cx) || $cy cmp $cx)
  108.     );
  109. }
  110.  
  111. sub main'badd { #(num_str, num_str) return num_str
  112.     local(*x, *y); ($x, $y) = (&'bnorm($_[0]),&'bnorm($_[1]));
  113.     if ($x eq 'NaN') {
  114.     'NaN';
  115.     } elsif ($y eq 'NaN') {
  116.     'NaN';
  117.     } else {
  118.     @x = &internal($x);             # convert to internal form
  119.     @y = &internal($y);
  120.     local($sx, $sy) = (shift @x, shift @y); # get signs
  121.     if ($sx eq $sy) {
  122.         &external($sx, &add(*x, *y)); # if same sign add
  123.     } else {
  124.         ($x, $y) = (&abs($x),&abs($y)); # make abs
  125.         if (&cmp($y,$x) > 0) {
  126.         &external($sy, &sub(*y, *x));
  127.         } else {
  128.         &external($sx, &sub(*x, *y));
  129.         }
  130.     }
  131.     }
  132. }
  133.  
  134. sub main'bsub { #(num_str, num_str) return num_str
  135.     &'badd($_[0],&'bneg($_[1]));    
  136. }
  137.  
  138. # GCD -- Euclids algorithm Knuth Vol 2 pg 296
  139. sub main'bgcd { #(num_str, num_str) return num_str
  140.     local($x,$y) = (&'bnorm($_[0]),&'bnorm($_[1]));
  141.     if ($x eq 'NaN' || $y eq 'NaN') {
  142.     'NaN';
  143.     } else {
  144.     ($x, $y) = ($y,&'bmod($x,$y)) while $y ne '+0';
  145.     $x;
  146.     }
  147. }
  148.  
  149. # routine to add two base 1e5 numbers
  150. #   stolen from Knuth Vol 2 Algorithm A pg 231
  151. #   there are separate routines to add and sub as per Kunth pg 233
  152. sub add { #(int_num_array, int_num_array) return int_num_array
  153.     local(*x, *y) = @_;
  154.     $car = 0;
  155.     for $x (@x) {
  156.     last unless @y || $car;
  157.     $x -= 1e5 if $car = (($x += shift(@y) + $car) >= 1e5);
  158.     }
  159.     for $y (@y) {
  160.     last unless $car;
  161.     $y -= 1e5 if $car = (($y += $car) >= 1e5);
  162.     }
  163.     (@x, @y, $car);
  164. }
  165.  
  166. # subtract base 1e5 numbers -- stolen from Knuth Vol 2 pg 232, $x > $y
  167. sub sub { #(int_num_array, int_num_array) return int_num_array
  168.     local(*sx, *sy) = @_;
  169.     $bar = 0;
  170.     for $sx (@sx) {
  171.     last unless @y || $bar;
  172.     $sx += 1e5 if $bar = (($sx -= shift(@sy) + $bar) < 0);
  173.     }
  174.     @sx;
  175. }
  176.  
  177. # multiply two numbers -- stolen from Knuth Vol 2 pg 233
  178. sub main'bmul { #(num_str, num_str) return num_str
  179.     local(*x, *y); ($x, $y) = (&'bnorm($_[0]), &'bnorm($_[1]));
  180.     if ($x eq 'NaN') {
  181.     'NaN';
  182.     } elsif ($y eq 'NaN') {
  183.     'NaN';
  184.     } else {
  185.     @x = &internal($x);
  186.     @y = &internal($y);
  187.     local($signr) = (shift @x ne shift @y) ? '-' : '+';
  188.     @prod = ();
  189.     for $x (@x) {
  190.         ($car, $cty) = (0, 0);
  191.         for $y (@y) {
  192.         $prod = $x * $y + $prod[$cty] + $car;
  193.         $prod[$cty++] =
  194.             $prod - ($car = int($prod * 1e-5)) * 1e5;
  195.         }
  196.         $prod[$cty] += $car if $car;
  197.         $x = shift @prod;
  198.     }
  199.     &external($signr, @x, @prod);
  200.     }
  201. }
  202.  
  203. # modulus
  204. sub main'bmod { #(num_str, num_str) return num_str
  205.     (&'bdiv(@_))[1];
  206. }
  207.  
  208. sub main'bdiv { #(dividend: num_str, divisor: num_str) return num_str
  209.     local (*x, *y); ($x, $y) = (&'bnorm($_[0]), &'bnorm($_[1]));
  210.     return wantarray ? ('NaN','NaN') : 'NaN'
  211.     if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0');
  212.     return wantarray ? ('+0',$x) : '+0' if (&cmp(&abs($x),&abs($y)) < 0);
  213.     @x = &internal($x); @y = &internal($y);
  214.     $srem = $y[0];
  215.     $sr = (shift @x ne shift @y) ? '-' : '+';
  216.     $car = $bar = $prd = 0;
  217.     if (($dd = int(1e5/($y[$#y]+1))) != 1) {
  218.     for $x (@x) {
  219.         $x = $x * $dd + $car;
  220.         $x -= ($car = int($x * 1e-5)) * 1e5;
  221.     }
  222.     push(@x, $car); $car = 0;
  223.     for $y (@y) {
  224.         $y = $y * $dd + $car;
  225.         $y -= ($car = int($y * 1e-5)) * 1e5;
  226.     }
  227.     }
  228.     else {
  229.     push(@x, 0);
  230.     }
  231.     @q = (); ($v2,$v1) = @y[$#y-1,$#y];
  232.     while ($#x > $#y) {
  233.     ($u2,$u1,$u0) = @x[($#x-2)..$#x];
  234.     $q = (($u0 == $v1) ? 99999 : int(($u0*1e5+$u1)/$v1));
  235.     --$q while ($v2*$q > ($u0*1e5+$u1-$q*$v1)*1e5+$u2);
  236.     if ($q) {
  237.         ($car, $bar) = (0,0);
  238.         for ($y = 0, $x = $#x-$#y-1; $y <= $#y; ++$y,++$x) {
  239.         $prd = $q * $y[$y] + $car;
  240.         $prd -= ($car = int($prd * 1e-5)) * 1e5;
  241.         $x[$x] += 1e5 if ($bar = (($x[$x] -= $prd + $bar) < 0));
  242.         }
  243.         if ($x[$#x] < $car + $bar) {
  244.         $car = 0; --$q;
  245.         for ($y = 0, $x = $#x-$#y-1; $y <= $#y; ++$y,++$x) {
  246.             $x[$x] -= 1e5
  247.             if ($car = (($x[$x] += $y[$y] + $car) > 1e5));
  248.         }
  249.         }   
  250.     }
  251.     pop(@x); unshift(@q, $q);
  252.     }
  253.     if (wantarray) {
  254.     @d = ();
  255.     if ($dd != 1) {
  256.         $car = 0;
  257.         for $x (reverse @x) {
  258.         $prd = $car * 1e5 + $x;
  259.         $car = $prd - ($tmp = int($prd / $dd)) * $dd;
  260.         unshift(@d, $tmp);
  261.         }
  262.     }
  263.     else {
  264.         @d = @x;
  265.     }
  266.     (&external($sr, @q), &external($srem, @d, 0));
  267.     } else {
  268.     &external($sr, @q);
  269.     }
  270. }
  271. 1;
  272.