#!/usr/bin/perl use strict; use warnings; # Non-recursive method for generating Fibonacci series # # This is based on one liner found here: # http://3monkeyweb.com/3monkeys/2007/07/12/fibonacci-series-in-one-line-of-perl/ # # Amendments and comments made by Victor Odlivak 8/2/7 # # usage: ./perl_no_recur_fib i # # where i is an integer between 0 and 73. # # This is the one liner: #perl -e'@p=(0,1);until($#p>74){print"$p[-2]\n";push @p,$p[-2]+$p[-1]}' #Here it is in a more intelligible form: sub Fibonacci { # # input = number of iterations, followed by array. # output = the last Fibonacci element for this iteration. # i.e. Fib(5) = 5 # Fib(0) = 0 # Fib(1) = 1; # Fib(2) = 1; # Fib(3) = 2; my ($num_iterations, @p) = @_; until($#p>$num_iterations) # loop through array as it grows. { # Note, $#p is the last index value of the array "p"; # Note, the Fibonacci array starts with last index of 1 # for [0, 1] and progresses by one every time we go # through the loop. We are using the fact that the push # had the side effect of incrementing the the count of the # last index. #print "this is dollar_pound_p; $#p \n"; push @p,$p[-2]+$p[-1]; # add two elements of array and push at end. } return "$p[-2]"; } #Main Section my $number_of_iterations = shift@ARGV; my $result = 0; my @q = (0,1); #starting Fibonacci array. Note, you can # start later in the sequence if you like, i.e. (5,8) unless ($number_of_iterations) { print "Sorry, you forgot to enter the number of iterations "; print "for the Fibonacci series. i.e.: ./perl_no_recur_fib 10 \n"; exit; } if (($number_of_iterations > 73) or ($number_of_iterations < 0)) { print "iterations must be between 0 and "; print " 73 for accurate values.\n"; exit; } $result = Fibonacci($number_of_iterations, @q); print "Fibonacci($number_of_iterations) element of the series = "; print "$result \n"; exit;