Skip to content

Instantly share code, notes, and snippets.

@wchristian
Created March 16, 2011 13:19
Show Gist options
  • Save wchristian/872476 to your computer and use it in GitHub Desktop.
Save wchristian/872476 to your computer and use it in GitHub Desktop.
use strict;
use warnings;
use Benchmark 'timethis';
timethis( -5, sub { f(18) }, 'fibonacci' );
sub fib {
return $_[0] < 2 ? $_[0] : fib($_[0]-1) + fib($_[0]-2)
}
# Subroutine f(n) handles the negative arguments: F(-n) = F(n)*(-1)^(n+1)
sub f {
if ($_[0] < 0) {
return $_[0] % 2 ? fib(-$_[0]) : -fib(-$_[0]);
} else {
return fib($_[0]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment