Using a PHP iterator to implement a Fibonacci sequence

Source: Internet
Author: User

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?
01 /**
02 * @author 简明现代魔法 http://www.nowamagic.net
03 */
04 classFibonacci implementsIterator {
05 private$previous= 1;
06 private$current= 0;
07 private$key= 0;
08
09 publicfunctioncurrent() {
10 return$this->current;
11 }
12
13 publicfunctionkey() {
14 return$this->key;
15 }
16
17 publicfunctionnext() {
18 // 关键在这里
19 // 将当前值保存到 $newprevious
20 $newprevious= $this->current;
21 // 将上一个值与当前值的和赋给当前值
22 $this->current += $this->previous;
23 // 前一个当前值赋给上一个值
24 $this->previous = $newprevious;
25 $this->key++;
26 }
27
28 publicfunctionrewind() {
29 $this->previous = 1;
30 $this->current = 0;
31 $this->key = 0;
32 }
33
34 publicfunctionvalid() {
35 returntrue;
36 }
37 }
38
39 $seq= newFibonacci;
40 $i= 0;
41 foreach($seq as$f) {
42 echo"$f ";
43 if($i++ === 15) break;
44 }

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.