Logo

Programming-Idioms

  • Python
  • Perl

Idiom #301 Recursive Fibonacci sequence

Compute the Fibonacci sequence of n numbers using recursion.

Note that naive recursion is extremely inefficient for this task.

sub fib {
    my ($n) = @_;
    die if $n < 0;
    return 1 if $n < 2;
    return fib($n-1) + fib($n-2);
}
def fib(n):
    if n < 0:
        raise ValueError
    if n < 2:
        return n
    return fib(n - 2) + fib(n - 1)
        
int fibonacci(int n) => n <= 2 ? 1 : fibonacci(n - 2) + fibonacci(n - 1);

New implementation...
< >
Sikon