Page 1 of 1

Fibonacci Sequence PHP

Posted: Fri Feb 01, 2008 10:40 am
by jamesrocks
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!!

Re: Fibonacci Sequence PHP

Posted: Fri Feb 01, 2008 10:56 am
by Oren
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}

Re: Fibonacci Sequence PHP

Posted: Fri Feb 01, 2008 1:07 pm
by JAM

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>
Edited: Unneeded var stripped. Thanks for headsup. ;)

Re: Fibonacci Sequence PHP

Posted: Fri Feb 01, 2008 11:54 pm
by nickvd
jamesrocks 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!!
Sounds like homework to me :)

You learn better by trial and error! :)

Re: Fibonacci Sequence PHP

Posted: Sat Feb 02, 2008 9:02 am
by dml
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

Posted: Sat Feb 02, 2008 3:49 pm
by Oren
$inc doesn't do anything anyway - you can get rid of it :P