Tuesday, April 14, 2009

Php: Adding integer with big number

I'm giving a function that you can use to perform addition arithmetic. This adding will be between a big number and a integer(32 bit). The big number will be a string, and the integer is as like php integer value. Here is the function

function add( $big_num_str, $to_add){
## reverse the string, and transfrom into array
$big_num = preg_split('//', strrev($big_num_str));

## adding the number with array
for($i = 1; $i < count($big_num) ; $i++){
$tmp = $big_num[$i] + $to_add;
$big_num[$i] = $tmp % 10;
$to_add = floor( $tmp / 10 );

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

## transform from array to string, and revers
return strrev( implode('', $big_num) );

To use the code, here is few example
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";

Inside the add() function, I have taken the big number as string. Then reverse it using strrev() function, and transform the string into an array of PHP. After that I have performed the addition part with the array(considering the array as number).

After performing the addition, I have transformed the array into string again, and then reversed it before return, so that it will be on its original format.

Its always easy to add two big number using array. But when you need to add one integer with a big number, then its a problem. I think my example will be helpful for you to perform big number addition arithmetic with a normal integer.

You can enhance the function to handle floating point number. Or may be next any day I can write that myself if I need, and will share with you. Till then... Enjoy the function!!!

No comments:

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...