斐波那契数列,使用PHP迭代器、生成器实现

本文介绍了斐波那契数列的数学定义,并通过PHP编程展示了两种实现方式:一是利用for循环的普通解法,二是采用PHP的迭代器接口,详细解释了继承Iterator接口并实现相关方法的过程。此外,还探讨了PHP生成器的使用,通过yield关键字实现斐波那契数列的生成,强调了其在内存效率和代码执行流程上的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

斐波那契数列其数学定义为:F0=1,F1=1,Fn=F(n-1)+F(n-2)(n>=2)

普通解法for循环

<?php 
$arr[1] = 1;
for($i = 2;$i < 100;$i++)
{
    $arr[$i] = $arr[$i-1] + $arr[$i-2];
}
echo join(",",$arr);//将数组合并为一个字符串输出
?>

PHP 迭代器

PHP 迭代器 继承Iterator 接口,实现5个方法即可
而生成器循环返回的是中间值

class Fb implements Iterator
{
    public function __construct($len)
    {
        $this->len = $len;
    }
    private $len = 0;
    private $pre = 1;
    private $curr = 1;
    private $count = 0;

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

    public function next()
    {
        $tmp = $this->curr;
        $this->curr += $this->pre;
        $this->pre = $tmp;
        $this->count++;
    }

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

    public function valid()
    {
        return $this->count < $this->len;
    }

    public function rewind()
    {
        $this->pre = 1;
        $this->curr = 1;
    }
}

foreach ((new Fb(40)) as $value) {
    echo $value . "\n";
}

PHP生成器

生成器使用yield关键字返回结果,和python一样。yield会直接返回结果,下次调用时会从上次yield处继续执行。

function Fb($len)
{
    $pre = 1;
    $curr = 1;
    $count = 1;
    while ($count <= $len) {
        yield $curr;
        $tmp = $curr;
        $curr += $pre;
        $pre = $tmp;
        $count++;
    }
}

foreach (Fb(40) as $value) {
    echo $value . "\n";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值