calculate 1000th element of standard Fibonacci sequence : Recursive « Subroutine « Perl






calculate 1000th element of standard Fibonacci sequence

   

#!/usr/bin/perl
use warnings;
use strict;

sub fibonacci3 {
    my ($count, $aref) = @_;
    
    unless ($aref) {
        # first call - initialize
        $aref = [1,1];
        $count -= scalar(@{$aref});
    }

    if ($count--) {
        my $next = $aref->[-1] + $aref->[-2];
        push @{$aref}, $next;
        @_ = ($count, $aref);
        goto &fibonacci3;
    } else {
        return wantarray?@{$aref}:$aref->[-1];
    }
}

print scalar(fibonacci3(1000)), "\n";

   
    
    
  








Related examples in the same category

1.Recursive factorial subroutine
2.Recursive fibonacci function.
3.Recursive subroutine
4.Write recursive subroutines
5.factorial with recursive function
6.A recursive subroutine to perform arithmetic.