加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

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

发布时间:2020-05-24 12:10:32 所属栏目:PHP 来源:互联网
导读:斐波纳契数列通常做法是用递归实现,当然还有其它的方法。这里现学现卖,用PHP的迭代器来实现一个斐波纳契数列,几乎没有什么难度,只是把类里的next()方法重写了一次。注释已经写到代码中,也是相当好理解的

代码如下: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;
}

程序运行结果:
代码如下:0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读