#!/usr/bin/perl # Make a big Pascal's Triangle. require "cgi-bin/cgi_handlers.pl"; &get_request; $rqpairs{'rows'} ||=5; print <Pascal's Triangle

Interactive Pascal's Triangle

Show up to this row:
EOF print ("
"); &draw_pascals_triangle($rqpairs{'rows'}+3); print ("

"); print <non-interactive version if you want to.

Also, check out this colorful version from CECM/IMpress (Simon Fraser University).

EOF #################################################### sub draw_pascals_triangle { my $rows = shift @_; my $MAXROWS = 100; $rows = ($rows < 2 ? 2 : $rows); $rows = ($rows > $MAXROWS ? $MAXROWS : $rows); my $maxdigits = &find_max_digits($rows - 3); print ("1\n"); my @prevrow = (1); my @thisrow; for ($i=3; $i<$rows; $i++) { push(@thisrow, 1); for ($j=0; $j<@prevrow; $j++) { push (@thisrow, $prevrow[$j] + $prevrow[$j+1]); } foreach $item (@thisrow) { print(" ", &pad_center($item, $maxdigits)); } print ("\n"); @prevrow = @thisrow; @thisrow = (); } } sub pad_center{ my $item = shift @_; my $n = shift @_; my $half = int(($n-length($item))/2); return " "x$half . $item . " "x($n-length($item)-$half); } sub find_max_digits { my $lastrow = shift @_; my $half = int($lastrow/2); my $top = join("*", ($half+1 .. $lastrow)); my $bottom = join("*", (1 .. $half)); # print ("TOP: $top
BOTTOM: $bottom
\n"); return length eval("$top/($bottom)"); }