用PHP迭代器來實現一個斐波納契數列

gxfw 9年前發布 | 678 次閱讀 PHP

斐波納契數列通常做法是用遞歸實現,當然還有其它的方法。這里現學現賣,用PHP的迭代器來實現一個斐波納契數列,幾乎沒有什么難度,只是把類里的next()方法重寫了一次。注釋已經寫到代碼中,也是相當好理解的。

    <?php
/ @author nicesunboy@gmail.com */
class Fibonacci implements Iterator {
private $previous = 1;
private $current = 0;
private $key = 0;

    public function current() {   
        return $this->current;   
    }   

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

    public function next() {   
        // 關鍵在這里  
        // 將當前值保存到  $newprevious  
        $newprevious = $this->current;   
        // 將上一個值與當前值的和賦給當前值  
        $this->current += $this->previous;   
        // 前一個當前值賦給上一個值  
        $this->previous = $newprevious;   
        $this->key++;   
    }   

    public function rewind() {   
        $this->previous = 1;   
        $this->current = 0;   
        $this->key = 0;   
    }   

    public function valid() {   
        return true;   
    }   
}   

$seq = new Fibonacci;   
$i = 0;   
foreach ($seq as $f) {   
    echo "$f ";   
    if ($i++ === 15) break;   
}   
?>  </pre> 


程序運行結果:

    0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610  

 本文由用戶 gxfw 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!