#!/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.
The Fibonacci sequence starts with
f(0) = 0andf(1) = 1. After that each Fibonacci number is the sum of the previous two.Your function uses
return (1) if ($num <= 1)which incorrectly evaluatesf(0)as 1. If you change this toreturn $num if $num <= 1then your sequence will start correctly.This code outputs the first eleven numbers in the series.
output