统计总和的几种方法比较
//1:线性递归
function sumRecursion(int $n): int{
if($n < 1){
return 0;
}
return sumRecursion($n-1) + $n-1;
}
//2:线性迭代
function sumFor(int $n): int{
$sum = 0;
for($i=1;$i<=$n;$i++){
$sum+=$i;
}
return $sum;
}
//3:算法
function sum(int $n): int{
return ($n+1) * $n / 2;
}
//方法一直接报错
$number = 10000000;
$t1 = microtime(true);
$res = sumRecursion($number);
$t2 = microtime(true);
echo '耗时'.round($t2-$t1,3).'秒';
var_dump($res);
Fatal error: Uncaught Error: Maximum function nesting level of '256' reached, aborting!
//方法二耗时四秒多
$number = 10000000;
$t1 = microtime(true);
$res = sumFor($number);
$t2 = microtime(true);
echo '耗时'.round($t2-$t1,3).'秒';
var_dump($res);
耗时4.335秒 G:\study\sum.php:27:int 50000005000000
//使用算法,答案秒出
$number = 10000000;
$t1 = microtime(true);
$res = sum($number);
$t2 = microtime(true);
echo '耗时'.round($t2-$t1,3).'秒';
var_dump($res);
耗时0秒 G:\study\sum.php:27:int 50000005000000
网友评论