0 Replies - 1473 Views - Last Post: 08 January 2011 - 02:26 PM

#1 xTorvos   User is offline

  • D.I.C Regular
  • member icon

Reputation: 61
  • View blog
  • Posts: 271
  • Joined: 23-October 09

Nth Fibonacci Number

Posted 08 January 2011 - 02:26 PM

Description: Code was tested using: print &nth_fib($number). Just pass it a number and watch as it returns that Fib number.Returns the nth number in the Fibonacci sequence.
sub nth_fib
{
  #Check for positive input
  die "Error: Argument must be positive" unless $_[0] >= 0;
  
  my $n = shift;
  my $fib1 = 0;
  my $fib2 = 1;
  my $fib3 = 1;
  
  foreach (1..$n)
  {
    $fib3 = $fib1 + $fib2;
    $fib1 = $fib2;
    $fib2 = $fib3;
  }
  
  $fib1;
}

Is This A Good Question/Topic? 0
  • +

Page 1 of 1