The Fibonacci sequence is usually done recursively, and of course there are other methods. This is now learning to sell, using a PHP iterator to implement a Fibonacci sequence, with little difficulty, just rewrite the next () method in the class. Comments have been written into the code and are quite well understood. Dingzhou Technology Industry Bureau
View Source print?
02 |
* @author 简明现代魔法 http://www.nowamagic.net |
04 |
class Fibonacci implements Iterator { |
09 |
public function current() { |
17 |
public function next() { |
19 |
// 将当前值保存到 $newprevious |
20 |
$newprevious = $this ->current; |
22 |
$this ->current += $this ->previous; |
24 |
$this ->previous = $newprevious ; |
28 |
public function rewind () { |
34 |
public function valid() { |
43 |
if ( $i ++ === 15) break ; |
Program Run Result:
View Source print?
1 |
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 |
Using a PHP iterator to implement a Fibonacci sequence