factorial with recursive function : Recursive « Subroutine « Perl

Home
Perl
1.Array
2.CGI
3.Class
4.Data Type
5.Database
6.File
7.GUI
8.Hash
9.Language Basics
10.Network
11.Regular Expression
12.Report
13.Statement
14.String
15.Subroutine
16.System Functions
17.Win32
18.XML
Perl » Subroutine » Recursive 




factorial with recursive function
   
#!/usr/bin/perl

use warnings;
use strict;

sub fibonaccil {
    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;
        return fibonaccil($count, $aref);
    else {
        return wantarray?@{$aref}: $aref->[-1];
    }
}

print scalar(fibonaccil(10))"\n";
print scalar(fibonaccil(10[24]))"\n";
my @sequence = fibonaccil(10);
print "Sequence: @sequence \n";


sub fibonacci2 {
    my ($count, $internal= @_;

    if ($count <= 2) {
        return $internal ? [1,11;
    else {
        my $result = fibonacci2($count -1'internal'); 
        my $next = $result->[-1+ $result->[-2];

        if ($internal) {
            push @{$result}, $next;
            return $result;
        else {
            return $next;
        }
    }
}

foreach (1..20) {
    print "Element $_ is ", fibonacci2($_)"\n";
}

   
    
    
  














Related examples in the same category
1.Recursive factorial subroutine
2.Recursive fibonacci function.
3.Recursive subroutine
4.Write recursive subroutines
5.calculate 1000th element of standard Fibonacci sequence
6.A recursive subroutine to perform arithmetic.
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.