in reply to Re: fibonacci numbers using subroutine?
in thread fibonacci numbers using subroutine?

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>

Replies are listed 'Best First'.
Re^3: fibonacci numbers using subroutine?
by JavaFan (Canon) on Aug 20, 2010 at 12:59 UTC
    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>
        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.
        Actually, most mathematical definitions I've seen are of the form:
            F0 = 0
            F1 = 1
            Fn = Fn-1 + Fn-2, n > 1
        
        which to me doesn't smell like recursion at all. F is defined as a sequence, it's not defined as a function. It's more a way of declaring a list, or an array, if you want to find a programming equivalent. Something like:
        F[0] = 0; F[1] = 1; F[$_] = F[$_-1] + F[$_-2] for 1 .. *;
        (borrowing Perl6's *).