Perl: Big number addition with a simple integer number

At my last post, I have written about addition of a big number with a normal integer using PHP, http://icfun.blogspot.com/2009/04/php-adding-integer-with-big-number.html

I have converted the code into Perl for you if you need. The details of the function is as before. But once again just for a reminder. The function add() will take a big number as string format, and another number as integer format. After addition with the number with string formatted big number, it will return the result as string. Here is the Perl code for you.

sub add{
my ( $big_num_str, $to_add) = @_;

## reverse the string, and transfrom into array
my @big_num = split(//, reverse($big_num_str));

my $i = 0;
## adding the number with array
for($i = 0; $i <= $#big_num ; $i++){
my $tmp = $big_num[$i] + $to_add;
$big_num[$i] = $tmp % 10;
$to_add = int( $tmp / 10 );
}

## putting rest of the number from hand
while($to_add){
$big_num[ $i++ ] = $to_add % 10;
$to_add = int( $to_add / 10 );
}

## transform from array to string, and revers
return reverse( join('', @big_num) );
}


TO call the function, here is few example using Perl.
print add("10", 10000000) . "\n";
print add("0", 10000000) . "\n";
print add("", 10000000) . "\n";
print add("999999999999999", 10000000) . "\n";
print add("9999999999999999999999999999999999999999999", 10000000) . "\n";
print add("0009", 10) . "\n";


Hope some day, i'll convert the code into other languages for you guys.

Comments

Anonymous said…
Or you could install Math::BigInt from CPAN, and do:

perl -MMath::BigInt -le'my $m = Math::BigInt->new("999999999999999"); $m->badd(10000000); print $m'

Jess
rho said…
Ok, apart from the obvious Math::BigInt tangent:


## putting rest of the number from hand
while($to_add){
$big_num[ $i++ ] = $to_add % 10;
$to_add = int( $to_add / 10 );
}


This is just insane. Why not prepend the $to_add
to the result?
rho said…
I could not stop myself from fiddling with this code:

UnPerlish UnLaziness
Anonymous said…
Instead of using Math::BigInt directly you can also using it indirectly.

perl -Mbigint -le 'print 999999999999999 + 10000000'