in reply to fibonacci numbers using subroutine?

Problem is, I can already get it fine without a subroutine, and I can't figure out a way to get it with a subroutine without messing up my code.

You are creating a recursive function so throw away your code, get a piece of paper, and write

sub Fibonacci { my $n = shift; ... }
then replace ... with an if/else structure that either returns a number, or adds the return value of a call to Fibonacci( $n ... ) ...it should follow closely the mathematical definition for Fibonacci number.

Replies are listed 'Best First'.
Re^2: fibonacci numbers using subroutine?
by alexbio (Monk) on Aug 20, 2010 at 10:35 UTC

    I agree, recursive function follows better the mathematical definition and is easier to implement (no useless loop).

    Here is an example (if anyone is interested as derpp solved):

    sub fibonacci { my $n = shift; return undef if $n < 0; my $f; if ($n == 0) { $f = 0; } elsif ($n == 1) { $f = 1; } else { $f = fibonacci($n-1) + fibonacci($n-2); } return $f; } print fibonacci(25);
    Alessandro Ghedini <http://ghedini.co.cc>
      recursive function follows better the mathematical definition and is easier to implement (no useless loop).
      Fibonacci is a prime example why recursion can be very, very bad. For instance, your fibonacci(25) call results in 242785 calls to fibonacci. This doesn't scale.

      Even the most naïve loop implementation only execute its body 25 times. And it only takes two lines:

      my ($f, $fn) = (0, 1); ($f, $fn) = ($fn, $f + $fn) for 1 .. 25; print $f;
      And there's a formula that does the calculation in constant time.:
      my $PHI = (1 + sqrt(5)) / 2; Fibonnaci(N) = ($PHI ** $N - (1 - $PHI) ** $N) / sqrt(5);
      And since 1 < $PHI < 2, that can be written as:
      Fibonnaci(N) = int(0.5 + $PHI ** $N / sqrt(5))
      The only disadvantage the closed form has that for (on a 64 bit platform), for values > 84, the closed form suffers from rounding errors. But then, for values > 93, the result no longer fits in 64 bits integers, so precision is lost either way.

      † That assuming all arithmetic operations take constant time. This isn't quite true - it shuffles the size of the numbers under the carpet. There's a log(N) factor assumed (log(N) is the number of bits needed to store N).

        I've never said it's the best solution, but only that it follows better the Fibonacci mathematical definition and that it's easier (theoretically) to implement.

        But thanks for pointing that things out, I should have done it by myself.

        P.S. Yeah, maybe the "no useless loop" wasn't that right as I thought :D

        Alessandro Ghedini <http://ghedini.co.cc>