3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでフィボナッチ数列を再帰で解く+メモ化再帰と比較

Posted at

PHPでフィボナッチ数列を再帰で解く+メモ化再帰と比較

コード

/* 
フィボナッチ数列
 */

echo 'メモ化再帰を使わない場合のgetFib(35)を求める';
echo '<br>';
$startTime = microtime(true);
echo 'getFib(35)の答えは' . getFib(35);
$endTime = microtime(true);
$deltaTime = $endTime - $startTime;
echo('<br>処理にかかった時間は' . $deltaTime . 'ミリ秒です');
echo '<br><br>';
echo 'メモ化再帰を使った場合のgetFibByMemo(35)を求める';
echo '<br>';
$startTime = microtime(true);
echo 'getFibByMemo(35)の答えは' . getFibByMemo(35);
$endTime = microtime(true);
$deltaTime = $endTime - $startTime;
echo('<br>処理にかかった時間は' . $deltaTime . 'ミリ秒です');
echo '<br><br>';
echo 'メモ化再帰であれば$n=100もイケちゃう!!<br>';
echo 'getFibByMemo(100)の答えは' . getFibByMemo(100);

function getFib($n) {
    if ($n == 0) {
        return 1;
    }
    if ($n ==1) {
        return 2;
    }
    return getFib($n - 1) + getFib($n -2);
}

$memo = array();
function getFibByMemo($n) {
    global $memo;
        if ($n == 0) {
        return 1;
    }
    if ($n ==1) {
        return 2;
    }
    if(isset($memo[$n])) {
        return $memo[$n];
    }
    return $memo[$n] = getFibByMemo($n - 1) + getFibByMemo($n -2);
}

結果

メモ化再帰を使わない場合のgetFib(35)を求める
getFib(35)の答えは24157817
処理にかかった時間は6.0225310325623ミリ秒です

メモ化再帰を使った場合のgetFibWithMemo(35)を求める
getFibByMemo(35)の答えは24157817
処理にかかった時間は9.0837478637695E-5ミリ秒です

メモ化再帰であれば$n=100もイケちゃう!!
getFibByMemo(100)の答えは9.2737269219308E+20

##参考サイト
http://www.slideshare.net/chokudai/wap-atcoder3

3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?