kiat has asked for the wisdom of the Perl Monks concerning the following question:
Hi Monks,
I've coded a program to print out Pascal Triangle numbers and would like to find out how the code can be improved or whether there's a more efficient way to write it.
I hope you won't laugh at my code :)
Thanks in advance.
kiat
I've coded a program to print out Pascal Triangle numbers and would like to find out how the code can be improved or whether there's a more efficient way to write it.
I hope you won't laugh at my code :)
I look forward to your comments and suggestions on how to improve the code.#!/usr/local/bin/perl print "Enter number of rows...\n"; chomp (my $rows = <>); print "You entered $rows for rows\n"; pascal($rows); sub pascal { my ($rows) = @_; print "1\n"; for (my $outer = 1; $outer <= $rows; $outer++) { my $inner = $outer; print "1" unless ($outer == 1); for ($i = 1; $i <= $inner; $i++) { my $denominator = factorial($i)*(factorial($inner-$i)); my $pascalnum = factorial($inner)/$denominator if ($denominator +!= 0); print " $pascalnum" if ($outer > 1); } print "1\n" unless ($outer == 1); } } sub factorial { my ($factorial) = @_; my $answer = $factorial; while ($factorial) { $factorial--; $answer *= $factorial unless ($factorial == 0); } return $answer; }
Thanks in advance.
kiat
Edit kudra, 2002-06-19 Corrected spelling in title
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Pascal triange...
by ton (Friar) on Jun 19, 2002 at 08:46 UTC | |
by Abigail-II (Bishop) on Jun 19, 2002 at 11:48 UTC | |
by Abigail-II (Bishop) on Jun 19, 2002 at 17:04 UTC | |
by Burak (Chaplain) on Dec 25, 2003 at 14:35 UTC | |
by kiat (Vicar) on Jun 19, 2002 at 13:40 UTC | |
by Abigail-II (Bishop) on Jun 19, 2002 at 13:59 UTC | |
by kiat (Vicar) on Jun 19, 2002 at 10:52 UTC | |
Re: Pascal triange...
by ariels (Curate) on Jun 19, 2002 at 09:09 UTC | |
Re: Pascal's triangle...
by gumby (Scribe) on Jun 19, 2002 at 13:33 UTC | |
Re: Pascal triange...
by gumby (Scribe) on Jun 19, 2002 at 09:10 UTC | |
by particle (Vicar) on Jun 19, 2002 at 11:25 UTC | |
by merlyn (Sage) on Jun 19, 2002 at 13:16 UTC | |
by jeffa (Bishop) on Jun 19, 2002 at 17:51 UTC | |
by particle (Vicar) on Jun 19, 2002 at 22:14 UTC | |
by YuckFoo (Abbot) on Jun 20, 2002 at 19:23 UTC | |
by gumby (Scribe) on Jun 19, 2002 at 11:45 UTC | |
by theorbtwo (Prior) on Jun 19, 2002 at 22:26 UTC | |
by gumby (Scribe) on Jun 19, 2002 at 10:40 UTC | |
Re: Pascal's triangle...
by YuckFoo (Abbot) on Jun 20, 2002 at 19:59 UTC | |
Re: Pascal triange...
by Zaxo (Archbishop) on Jun 19, 2002 at 09:16 UTC | |
Re: Pascal's triangle...
by Anonymous Monk on Dec 04, 2019 at 04:19 UTC |
Back to
Seekers of Perl Wisdom