A-A+

PHP迭代器实现斐波纳契数列的函数

2020年06月20日 我爱编程 暂无评论

斐波纳契数列通常做法是用递归实现,当然还有其它的方法。这里现学现卖,用PHP的迭代器来实现一个斐波纳契数列,几乎没有什么难度,只是把类里的next()方法重写了一次。注释已经写到代码中,也是相当好理解的。

  1. class Fibonacci implements Iterator {
  2.     private $previous = 1;
  3.     private $current = 0;
  4.     private $key = 0;
  5.     public function current() {
  6.         return $this->current;
  7.     }
  8.     public function key() {
  9.         return $this->key;
  10.     }
  11.     public function next() {
  12.   // 关键在这里
  13.   // 将当前值保存到  $newprevious
  14.         $newprevious = $this->current;
  15.   // 将上一个值与当前值的和赋给当前值
  16.         $this->current += $this->previous;
  17.   // 前一个当前值赋给上一个值
  18.         $this->previous = $newprevious;
  19.         $this->key++;
  20.     }
  21.     public function rewind() {
  22.         $this->previous = 1;
  23.         $this->current = 0;
  24.         $this->key = 0;
  25.     }
  26.     public function valid() {
  27.         return true;
  28.     }
  29. }
  30. $seq = new Fibonacci;
  31. $i = 0;
  32. foreach ($seq as $f) {
  33.     echo "$f ";
  34.     if ($i++ === 15) break;
  35. }

程序运行结果:

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

给我留言

Copyright © 四季博客 保留所有权利.   Theme  Ality

用户登录