In order to avoid redundant recursive function calls, the Fibonacci sequence is better calculated in an iterative fashion. The algorithm shown below calculates it in a way that would be similar to how you might remember it if you were asked to recite it.
In order for the algorithm to work, we still need to know that the first two numbers in the sequence are 1 and 1. The algorithm shortcuts this saying the 0th number is 0, and the 1st number is 1. So therefore the second number is 0+1 or 1. From there the algorithm works on a for loop. I've added a second parameter to the function. If the second parameter is not passed in or is not "yes" the function will return only the last number in the sequence. If it is set to "yes" it will return the first $num values in the sequence separated by commas. Without further ado, here's an iterative solution to the Fibonacci sequence:
David Stockton is a programmer for J.D. Edwards who enjoys working with PHP in his spare time. He's been coding for over 16 years and has nearly 4.5 years experience with PHP. He has been happily married for almost 3 years and is looking forward to trying to become a dad. He can be reached for questions or comments or additional tutorial suggestions at codewalker@davidstockton.com.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |