note 91888 deleted from function.bcadd by danbrown
| From: | danbrown@php.net | Date: | Thu, 16 Jul 2009 14:27:14 +0000 |
| Subject: | note 91888 deleted from function.bcadd by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-158370@lists.php.net to get a copy of this message | ||
Note Submitter: Nitrogen
----
I made this to add an unlimited size of integers together (meaning no decimals)..
This could be useful for those without the BCMath extension.
<?php
function Add($Num1='0',$Num2='0') {
// check if they're both plain numbers
if(!preg_match("/^\d+$/",$Num1)||!preg_match("/^\d+$/",$Num2)) return(0);
// remove zeroes from beginning of numbers
for($i=0;$i<strlen($Num1);$i++) if(@$Num1{$i}!='0') {$Num1=substr($Num1,$i);break;}
for($i=0;$i<strlen($Num2);$i++) if(@$Num2{$i}!='0') {$Num2=substr($Num2,$i);break;}
// reverse both numbers and get their lengths
$Num1=strrev($Num1);$Len1=strlen($Num1);
$Num2=strrev($Num2);$Len2=strlen($Num2);
// calculate which is the longest in length
$MLen=max($Len1,$Len2);
// $Rema is for storing the calculated numbers (helps to carry the remainder)
$Rema=array();
// pad the numbers so they equal the same length (both equal to $MLen)
for($i=$Len1;$i<$MLen;$i++) $Num1.='0';
for($i=$Len2;$i<$MLen;$i++) $Num2.='0';
// cycle through each digit adding them together and add them to $Rema accordingly
for($i=0;$i<$MLen;$i++) $Rema[$i]=(string)((int)$Num1{$i})+((int)$Num2{$i});
// cycle through $Rema and if the item contains 2 digits, then carry the first
// digit to the next item in $Rema
for($i=0;$i<count($Rema);$i++) {
$Rema2=str_split($Rema[$i]);
if(count($Rema2)>=2) {
$Rema[$i]=$Rema2[1];
@$Rema[$i+1]+=$Rema2[0];
}
}
// implode $Rema so it's a string and reverse it, this is the result!
return(strrev(implode($Rema)));
}
$A='5650175242508133742';
$B='2361030539975818701734615584174625';
printf(" Add(%s,%s); // %s\r\n",$A,$B, Add($A,$B));
printf("BCAdd(%s,%s); // %s\r\n",$A,$B,BCAdd($A,$B)); // build-in function
/*
This will print something similar to this..
Add(5650175242508133742,2361030539975818701734615584174625);
BCAdd(5650175242508133742,2361030539975818701734615584174625);
both of which should be followed by the answer:
2361030539975824351909858092308367
*/
?>
It was a fun experience making, and thought I'd share it.
Enjoy,
Nitrogen.