home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Web Server / Savant.exe / disk1 / data1.cab / Perl5 / perl5 / lib / bigint.pl < prev    next >
Encoding:
Perl Script  |  2001-02-23  |  8.2 KB  |  288 lines

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