Fibonacci Sequence PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jamesrocks
Forum Newbie
Posts: 1
Joined: Fri Feb 01, 2008 10:36 am

Fibonacci Sequence PHP

Post 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!!
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Re: Fibonacci Sequence PHP

Post 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}
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Re: Fibonacci Sequence PHP

Post 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. ;)
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

Post 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! :)
dml
Forum Contributor
Posts: 133
Joined: Sat Jan 26, 2008 2:20 pm

Re: Fibonacci Sequence PHP

Post 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";}
 
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Re: Fibonacci Sequence PHP

Post by Oren »

$inc doesn't do anything anyway - you can get rid of it :P
Post Reply