Fibonacci sequence subroutine returning one digit too high...PERL

Posted by beProactive on Stack Overflow See other posts from Stack Overflow or by beProactive
Published on 2012-06-11T22:33:55Z Indexed on 2012/06/11 22:40 UTC
Read the original article Hit count: 273

Filed under:
|
|
|
#!/usr/bin/perl -w
use strict;

sub fib {
    my($num) = @_;  #give $num to input array
    return(1) if ($num<=1);  #termination condition
    return($num = &fib($num-1) + &fib($num-2));  #should return sum of first "n" terms in the fibonacci sequence
}

print &fib(7)."\n";  #should output 20

This subroutine should be outputting a summation of the first "x" amount of terms, as specified by the argument to the sub. However, it's one too high. Does this have something to do with the recursion?

Thanks.

© Stack Overflow or respective owner

Related posts about perl

Related posts about math