斐波那契數列簡單版:
<?php
function fibonacci($n) {
if ($n <= 1) {
return $n;
}
return fibonacci($n-1) + fibonacci($n-2);
}
n
小於10,效能尚可。n
取大數,使用時間飆升。優化一下,空間換時間,已經計算出結果的存在陣列裡,複用。
<?php
function fibonacci($n) {
static $cache = [];
if (isset($cache[$n])) {
return $cache[$n];
}
if ($n <= 1) {
return $n;
}
$temp = fibonacci($n-1) + fibonacci($n-2);
$cache[$n] = $temp;
return $temp;
}
現在效能是夠了,但是如果n
取的數特別大,超出整型或浮點型的範圍,那就要改用字串儲存。要實現豎式加法。
<?php
function fibonacci($n) {
static $cache = [];
if (isset($cache[$n])) {
return $cache[$n];
}
if ($n <= 1) {
return $n;
}
$temp = stringAdd(fibonacci($n-1), fibonacci($n-2));
$cache[$n] = $temp;
return $temp;
}
function stringAdd($s1, $s2) {
$s1 = strval($s1);
$s2 = strval($s2);
$s1Length = strlen($s1);
$s2Length = strlen($s2);
$length = 0;
if ($s1Length > $s2Length) {
$length = $s1Length;
$s2 = str_pad($s2, $s1Length, '0', STR_PAD_LEFT);
} else {
$length = $s2Length;
$s1 = str_pad($s1, $s2Length, '0', STR_PAD_LEFT);
}
$returnRes = '';
$carry = 0;
for ($i=$length-1; $i>=0; $i--) {
$result = intval($s1[$i]) + intval($s2[$i]) + $carry;
$res = $result % 10;
$carry = floor($result / 10);
$returnRes = $res . $returnRes;
}
if ($carry > 0) {
return strval($carry) . $returnRes;
}
return $returnRes;
}
最終演算法。