Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Sep 2010
    Location
    The Twilight Zone
    Posts
    86
    Thanks
    17
    Thanked 2 Times in 2 Posts

    PHP Recursive Fibonacci Sequence

    Hey guys,

    I'm trying to write a recursive code that prints EACH value in the sequence leading up to the specified place. For example, if I enter 3, I will get

    0 1 1

    Here's what I have so far. It prints the nth number in the sequence- I don't know where to go from there.

    PHP Code:
    function fibRec($n){
    if(
    $n==1){
    return 
    0;
    }
    if(
    $n==2){
    return 
    1;
    }
    else{
    $sum fibRec($n-1)+fibRec($n-2);
    return 
    $sum;
    }

    }
    $fib fibRec(29);
    echo 
    $fib

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,980
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    Yeah, yours does appear to be short by one step. That will be because of this:
    PHP Code:
    if($n==1){
    return 
    0;

    Fibonacci(1) should be 1, not 0. Fibonacci of 0 is 0 though.
    I can see how you got here though, its a question of if your $n represents the number FROM 0 or INCLUDING 0.
    Changing it to this:
    PHP Code:
    if($n==0){
    return 
    0;
    }
    else if(
    $n<=2){
    return 
    1;

    With your standard $sum for the else, does provide me with the numbers as expected. I compared it against one I just wrote:
    PHP Code:
    function fibonacci($n)
    {
        
    $iResult 1;
        if (
    $n == 0)
        {
            
    $iResult 0;
        }
        else if (
    $n >= 2)
        {
            
    $iResult fibonacci($n 1) + fibonacci($n 2);
        }
        else if (
    $n 0)
        {
            
    $iResult pow(-1$n 1) * fibonacci(abs($n));
        }

        return 
    $iResult;

    And got the same result for both with the above modification (except for the negatives since the algorithm you are using doesn't include the negafibonacci series).


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •