Php implements code sharing of the Fibonacci series and the Fibonacci series

Source: Internet
Author: User

Php implements code sharing of the Fibonacci series and the Fibonacci series

The Fibonacci series refers to a series of 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,144,233,377,610,987,159, 17711, 28657,463 68 ........

This series starts from 3rd items, and each item is equal to the sum of the first two items.

F0 = 0, F1 = 1, Fn = F (n-1) + F (n-2)

Recursive version and non-recursive version.

<?php function fib($n){   $array = array();   $array[0] = 1;   $array[1] = 1;   for($i=2;$i<$n;$i++){     $array[$i] = $array[$i-1]+$array[$i-2];   }   print_r($array); } fib(10); echo "\n------------------\n"; function fib_recursive($n){   if($n==1||$n==2){return 1;}   else{     return fib_recursive($n-1)+fib_recursive($n-2);   } } echo fib_recursive(10); ?> 

As a programmer of C and java, when writing non-recursion for the first time, I forgot to add $ before the variable.

Output result

Array (   [0] => 1   [1] => 1   [2] => 2   [3] => 3   [4] => 5   [5] => 8   [6] => 13   [7] => 21   [8] => 34   [9] => 55 ) ------------------ 55 

Summary

The above is all the content about php code implementation of the Fibonacci series. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

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.