LoginSignup
10
8

More than 5 years have passed since last update.

PHPのイテレータでフィボナッチ数列を計算

Posted at

フィボナッチ数 - Wikipedia

定義通り再帰で実装すると、非常に非効率になることで知られる(ゆえにベンチマーク用に使われたりする)フィボナッチ数列計算ですが、イテレータで解いてみるテスト。

<?php

class Fib implements Iterator
{
    private $prevprev = -1, $prev = 1, $i = 0, $k = 0;

    function key() { return $this->k; }

    function current() { return $this->i = $this->prevprev + $this->prev; }

    function next() {
        $this->prevprev = $this->prev;
        $this->prev = $this->i;
        ++$this->k;
    }

    function rewind() {
        $this->prevprev = -1;
        $this->prev = 1;
        $this->k = 0;
    }

    function valid() { return true; }
}

$fib = new Fib;

foreach ($fib as $i => $v) {
    echo "$i\t$v\n";
    usleep(50000);
} //無限ループ

フィボナッチで各種言語をベンチマーク - satosystemsの日記

fib(38)が欲しいなら、LimitIteratorの合わせ技で求められるよ!

$fib38 = new LimitIterator(new Fib, 0, 38 + 1);
foreach ($fib38 as $_);

echo $_;
10
8
3

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
10
8