我需要使用长整数加上,现在我已经在字符串类型上创建了这个函数,但它要慢... 任何人都知道在字符串中计算加号的更好的解决方案吗?
这是我的功能:
function math_plus($first, $second)
{
$first = strrev($first); $first_length = strlen($first);
$second = strrev($second); $second_length = strlen($second);
$result = "";
if ($first_length > $second_length)
{
$big = $first; $big_length = $first_length;
$small = $second; $small_length = $second_length;
}
else
{
$big = $second; $big_length = $second_length;
$small = $first; $small_length = $first_length;
}
$memory_exists = false;
for ($i=0;$i < $big_length;$i++)
{
$small_exists = ($i < $small_length)?true:false;
$big_value = (int) substr($big, $i, 1);
$value = $big_value;
if ($small_exists)
{
$small_value = (int) substr($small, $i, 1);
$value += $small_value;
}
if ($memory_exists){$value++;$memory_exists = false;}
if ($value >= 10){$value -= 10; $memory_exists = true;}
$result = $value . $result;
}
if ($memory_exists)
{
$result = "1" . $result;
}
return $result;
}
$first = "325436746798098576787634576587568764355645645654634645746657676543";
$second = "325436746798098576787634576587568764355645645654634645746657676543";
echo math_plus($first, $second);
答案 0 :(得分:0)
使用BCMath:http://uk3.php.net/manual/en/function.bcadd.php
bcadd("1.00000", "2.00000");