NAME

Math::BigInt - Arbitrary size integer math package

SYNOPSIS

  use Math::BigInt;

  # Number creation	
  $x = Math::BigInt->new($str);	# defaults to 0
  $nan  = Math::BigInt->bnan(); # create a NotANumber
  $zero = Math::BigInt->bzero();# create a "+0"

  # Testing
  $x->is_zero();		# return wether arg is zero or not
  $x->is_nan();			# return wether arg is NaN or not
  $x->is_one();			# return true if arg is +1
  $x->is_one('-');		# return true if arg is -1
  $x->is_odd();			# return true if odd, false for even
  $x->is_even();		# return true if even, false for odd
  $x->bcmp($y);			# compare numbers (undef,<0,=0,>0)
  $x->bacmp($y);		# compare absolutely (undef,<0,=0,>0)
  $x->sign();			# return the sign, either +,- or NaN
  $x->digit($n);		# return the nth digit, counting from right
  $x->digit(-$n);		# return the nth digit, counting from left

  # The following all modify their first argument:

  # set 
  $x->bzero();			# set $x to 0
  $x->bnan();			# set $x to NaN

  $x->bneg();			# negation
  $x->babs();			# absolute value
  $x->bnorm();			# normalize (no-op)
  $x->bnot();			# two's complement (bit wise not)
  $x->binc();			# increment x by 1
  $x->bdec();			# decrement x by 1
  
  $x->badd($y);			# addition (add $y to $x)
  $x->bsub($y);			# subtraction (subtract $y from $x)
  $x->bmul($y);			# multiplication (multiply $x by $y)
  $x->bdiv($y);			# divide, set $x to quotient
				# return (quo,rem) or quo if scalar

  $x->bmod($y);			# modulus (x % y)
  $x->bpow($y);			# power of arguments (x ** y)
  $x->blsft($y);		# left shift
  $x->brsft($y);		# right shift 
  
  $x->band($y);			# bit-wise and
  $x->bior($y);			# bit-wise inclusive or
  $x->bxor($y);			# bit-wise exclusive or
  $x->bnot();			# bit-wise not (two's complement)
  
  # The following do not modify their arguments:

  bgcd(@values);		# greatest common divisor
  blcm(@values);		# lowest common multiplicator
  
  $x->bstr();			# return normalized string
  $x->length();			# return number of digits in number

DESCRIPTION

All operators (inlcuding basic math operations) are overloaded if you declare your big integers as

$i = new Math::BigInt '123 456 789 123 456 789';

Operations with overloaded operators preserve the arguments which is exactly what you expect.

Canonical notation

Big integer values are strings of the form /^[+-]\d+$/ with leading zeros suppressed.

'-0'                            canonical value '-0', normalized '0'
'   -123 123 123'               canonical value '-123123123'
'1 23 456 7890'                 canonical value '1234567890'
Input

Input values to these routines may be either Math::BigInt objects or strings of the form /^\s*[+-]?[\d\s]+\.?[\d\s]*E?[+-]?[\d\s]*$/.

This means integer values like 1.01E2 or even 1000E-2 are also accepted. Non integer values result in NaN.

Math::BigInt::new() defaults to 0, while Mah::BigInt::new('') results in 'NaN'.

bnorm() on a BigInt object is now effectively a no-op, since the numbers are always stored in normalized form. On a string, it creates a BigInt object.

Output

Output values are BigInt objects (normalized), except for bstr(), which returns a string in normalized form. Some routines (is_odd(), is_even(), is_zero(), is_one()) return true or false, while others (bcmp(), bacmp()) return either undef, <0, 0 or >0 and are suited for sort.

Actual math is done in an internal format consisting of an array of elements of base 100000 digits with the least significant digit first. The sign /^[+-]$/ is stored separately. The string 'NaN' is used to represent the result when input arguments are not numbers, as well as the result of dividing by zero.

EXAMPLES

use Math::BigInt qw(bstr bint);
$x = bstr("1234")                  	# string "1234"
$x = "$x";                         	# same as bstr()
$x = bneg("1234")                  	# Bigint "-1234"
$x = Math::BigInt->bneg("1234");   	# Bigint "-1234"
$x = Math::BigInt->babs("-12345"); 	# Bigint "12345"
$x = Math::BigInt->bnorm("-0 00"); 	# BigInt "0"
$x = bint(1) + bint(2);            	# BigInt "3"
$x = bint(1) + "2";                	# dito (auto-BigIntify of "2")
$x = bint(1);                      	# BigInt "1"
$x = $x + 5 / 2;                   	# BigInt "3"
$x = $x ** 3;                      	# BigInt "27"
$x *= 2;                           	# BigInt "54"
$x = new Math::BigInt;             	# BigInt "0"
$x--;                              	# BigInt "-1"
$x = Math::BigInt->badd(4,5)		# BigInt "9"
$x = Math::BigInt::badd(4,5)		# BigInt "9"

Autocreating constants

After use Math::BigInt ':constant' all the integer decimal constants in the given scope are converted to Math::BigInt. This conversion happens at compile time.

In particular

perl -MMath::BigInt=:constant -e 'print 2**100,"\n"'

prints the integer value of 2**100. Note that without conversion of constants the expression 2**100 will be calculated as floating point number.

Please note that strings and floating point constants are not affected, so that

  	use Math::BigInt qw/:constant/;

	$x = 1234567890123456789012345678901234567890
		+ 123456789123456789;
	$x = '1234567890123456789012345678901234567890'
		+ '123456789123456789';

do both not work. You need a explicit Math::BigInt->new() around one of them.

PERFORMANCE

Using the form $x += $y; etc over $x = $x + $y is faster, since a copy of $x must be made in the second case. For long numbers, the copy can eat up to 20% of the work (in case of addition/subtraction, less for multiplication/division). If $y is very small compared to $x, the form $x += $y is MUCH faster than $x = $x + $y since the copy of $x takes more time then the actual addition.

The new version of this module is slower on new(), bstr() and numify(). Some operations may be slower for small numbers, but are significantly faster for big numbers. Other operations are now constant (O(1), bneg(), babs() etc), instead of O(N) and thus nearly always take much less time.

For more benchmark results see http://bloodgate.com/perl/benchmarks.html

BUGS

:constant and eval()

Under Perl prior to 5.6.0 having an use Math::BigInt ':constant'; and eval() in your code will crash with "Out of memory". This is probably an overload/exporter bug. You can workaround by not having eval() and ':constant' at the same time, upgrade your Perl or find out why it happens ;)

CAVEATS

Some things might not work as you expect them. Below is documented what is known to be troublesome:

stringify, bstr()

Both stringify and bstr() now drop the leading '+'. The old code would return '+3', the new returns '3'. This is to be consistent with Perl and to make cmp (especially with overloading) to work as you expect. It also solves problems with Test.pm, it's ok() uses 'eq' internally.

Mark said, when asked about to drop the '+' altogether, or make only cmp work:

I agree (with the first alternative), don't add the '+' on positive
numbers.  It's not as important anymore with the new internal 
form for numbers.  It made doing things like abs and neg easier,
but those have to be done differently now anyway.

So, the following examples will now work all as expected:

	use Test;
        BEGIN { plan tests => 1 }
	use Math::BigInt;

	my $x = new Math::BigInt 3*3;
	my $y = new Math::BigInt 3*3;

	ok ($x,3*3);
	print "$x eq 9" if $x eq $y;
	print "$x eq 9" if $x eq '9';
	print "$x eq 9" if $x eq 3*3;

Additionally, the following still works:

print "$x == 9" if $x == $y;
print "$x == 9" if $x == 9;
print "$x == 9" if $x == 3*3;
bdiv

The following will probably not do what you expect:

print $c->bdiv(10000),"\n";

It prints both quotient and reminder since print works in list context. Also, bdiv() will modify $c, so be carefull. You probably want to use

print $c / 10000,"\n";
print scalar $c->bdiv(10000),"\n";  # or if you want to modify $c

instead.

The quotient is always the greatest integer less than or equal to the real-valued quotient of the two operands, and the remainder (when it is nonzero) always has the same sign as the second operand; so, for example,

1 / 4 => (0,1)
1 / -4 => (-1,-3)
-3 / 4 => (-1,1)
-3 / -4 => (0,-3)

As a consequence, the behavior of the operator % agrees with the behavior of Perl's built-in % operator (as documented in the perlop manpage), and the equation

$x == ($x / $y) $y + ($x % $y)

holds true for any $x and $y, which justifies calling the two return values of bdiv() the quotient and remainder.

Perl's 'use integer;' changes the behaviour of % and / for scalars, but will not change BigInt's way to do things. This is because under 'use integer' Perl will do what the underlying C thinks is right and this is different for each system. If you need BigInt's behaving exactly like Perl's 'use integer', bug the author to implement it ;)

bpow

bpow() now modifies the first argument, unlike the old code which left it alone and only returned the result. This is to be consistent with badd() etc. The first three will modify $x, the last one won't:

print bpow($x,$i),"\n"; 	# modify $x
print $x->bpow($i),"\n"; 	# dito
print $x **= $i,"\n";		# the same
print $x ** $i,"\n";		# leave $x alone 

The form $x **= $y is faster than $x = $x ** $y;, though.

Overloading -$x

The following:

$x = -$x;

is slower than

$x->bneg();

since overload calls sub($x,0,1); instead of neg($x). The first variant needs to preserve $x since it does not know that it later will get overwritten. This makes a copy of $x and takes O(N). But $x->bneg() is O(1).

Mixing differend object types

In Perl you will get a floating point value if you do one of the following:

$float = 5.0 + 2;
$float = 2 + 5.0;
$float = 5 / 2;

With overloaded math, only the first two variants will result in a BigFloat:

use Math::BigInt;
use Math::BigFloat;

$mbf = Math::BigFloat->new(5);
$mbi2 = Math::BigInteger->new(5);
$mbi = Math::BigInteger->new(2);

$float = $mbf + $mbi;		# $mbf->badd()
$float = $mbf / $mbi;		# $mbf->bdiv()
$integer = $mbi + $mbf;		# $mbi->badd()
$integer = $mbi2 / $mbi;	# $mbi2->bdiv()
$integer = $mbi2 / $mbf;	# $mbi2->bdiv()

This is because math with overloaded operators follows the first (dominating) operand, this one's operation is called and returns such the result. Thus, Math::BigInt::bdiv() will always return a Math::BigInt, regardless wether the result should be a Math::BigFloat or the second operant is one.

To get a Math::BigFloat you either need to call the operation manually, make sure the operands are already of the proper type or casted to that type via Math::BigFloat->new().

$float = Math::BigFloat->new($mbi2) / $mbi;	# = 2.5

Beware of simple "casting" the entire expression, this would only convert the already computed result:

$float = Math::BigFloat->new($mbi2 / $mbi);	# = 2.0 thus wrong!

Beware of the order of more complicated expressions like:

$integer = ($mbi2 + $mbi) / $mbf;		# int / float => int
$integer = $mbi2 / Math::BigFloat->new($mbi);	# dito

If in doubt, break the expression into simpler terms, or cast all operands to the desired resulting type.

Scalar values are a bit different, since:

$float = 2 + $mbf;
$float = $mbf + 2;

will both result in the proper type due to the way overload works.

This section also applies to other overloaded math packages, like Math::String.

AUTHORS

Original code by Mark Biggar, overloaded interface by Ilya Zakharevich. Completely rewritten by Tels http://bloodgate.com in late 2000, 2001.