#!/usr/bin/perl

# fibonacci_iterative($n) computes the $nth term of the Fibonacci
# sequence by computing all $n-1 terms.
#
sub fibonacci_iterative {
    my ($n) = shift;
    my ($i) = 2;
    my ($current, $old, $older) = (1,1);
    return 1 if $n <= 2;
    for ( ; $i < $n; $i++) {
        $older = $old;
        $old   = $current;
        $current = $old + $older;
    }
    return $current;
}

# fibonacci($n) computes the $nth term of the Fibonacci sequence directly.
#
sub fibonacci {
    my ($n, $s) = (shift, sqrt(5));
    return (((0.5 + 0.5*$s) ** $n) - ((0.5 - 0.5*$s) ** $n)) / $s;
}

print fibonacci_iterative(20), "\n";

print fibonacci(20), "\n";
