Anyone know the PHP for the Fibonacci Sequence?
Starts with 0, 1, 1, 2, 3, 5 , 8, 13, 21..... and needs to stop before it reaches 1000!
HELP!!
Thank you!!
Fibonacci Sequence PHP
Moderator: General Moderators
Re: Fibonacci Sequence PHP
What exactly you need?
All that matter here is that:
1) An = An-1 + An-2
2) A0 = 0
3) A1 = 1
Edit: None recursive formula for An (not sure cause I calculated it myself so there might be an error so double check before you use it):
An = {(1 / sqrt(5)) * [(1 + sqrt(5)) / 2]^n} - {(1 / sqrt(5)) * [(1 - sqrt(5)) / 2]^n}
All that matter here is that:
1) An = An-1 + An-2
2) A0 = 0
3) A1 = 1
Edit: None recursive formula for An (not sure cause I calculated it myself so there might be an error so double check before you use it):
An = {(1 / sqrt(5)) * [(1 + sqrt(5)) / 2]^n} - {(1 / sqrt(5)) * [(1 - sqrt(5)) / 2]^n}
Re: Fibonacci Sequence PHP
Code: Select all
<pre><?php
function calculate() {
list($i,$n,$d) = array(0,1,array());
while ($i < 1000) {
$d[] = $i;
$add = $i + $n;
$i = $n;
$n = $add;
}
print_r($d);
}
calculate();
?></pre>
Last edited by JAM on Sun Feb 03, 2008 2:56 am, edited 1 time in total.
-
nickvd
- DevNet Resident
- Posts: 1027
- Joined: Thu Mar 10, 2005 5:27 pm
- Location: Southern Ontario
- Contact:
Re: Fibonacci Sequence PHP
Sounds like homework to mejamesrocks wrote:Anyone know the PHP for the Fibonacci Sequence?
Starts with 0, 1, 1, 2, 3, 5 , 8, 13, 21..... and needs to stop before it reaches 1000!
HELP!!
Thank you!!
You learn better by trial and error!
Re: Fibonacci Sequence PHP
This is a better way of doing it performance-wise, as it doesn't require the numbers to be recalculated every time.
Code: Select all
foreach(array(0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987) as $n){echo "$n\n";}
Re: Fibonacci Sequence PHP
$inc doesn't do anything anyway - you can get rid of it 