Tuesday, February 24, 2009

plus function for large number

function plus($a,$b){
  $b_length = strlen($b)+1;
  $a = sprintf("%0".$b_length."s",   $a);
  $b = '0'.$b;
  $a_length = strlen($a);
  $temp =0;
  for($i=0;$i<$a_length;$i++){
    $a1 = substr($a,-1,1);
    $b1 = substr($b,-1,1);
    $a = substr($a,0,-1);
    $b = substr($b,0,-1);
    $result = ($a1+$b1+$temp)%10;
    $ans = $result.$ans;
    $temp = floor(($a1+$b1+$temp)/10);
  }
  $ans = $b.$ans;
  return ltrim($ans,'0');
}
with both $a and $b if string and strlen($a) < strlen($a)