其他分享
首页 > 其他分享> > 输出斐波纳契数列

输出斐波纳契数列

作者:互联网

方法一:迭代器
class myIterator implements Iterator {
    private $position = 0;
    private $current = 1;
    private $previous = 0;

    public function __construct(){}

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

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

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

    public function next()
    {
        $tem = $this->previous;
        $this->previous = $this->current;
        $this->current = $this->current + $tem;
        ++$this->position;
    }

    public function valid()
    {
        return ($this->current !== false);
    }
}
 
$it = new myIterator;
foreach($it as $key => $value) {
    // if ($key > 15) break;
    echo "$value    ";
}
方法二:生成器
function generator()
{
    $current = 1;
    $previous = 0;
    while ($current) {
        yield $current; // 重点在这里使用了yield
        $temp = $current;
        $current = $current + $previous;
        $previous = $temp;
    }
}

foreach (generator() as $key => $value) {
    // if ($key > 15) break;
    echo "$value    ";
}

标签:function,输出,数列,波纳契,value,current,key,public,previous
来源: https://www.cnblogs.com/phonecom/p/10345743.html