http://qs321.pair.com?node_id=176757

NodeReaper has asked for the wisdom of the Perl Monks concerning the following question:

This node falls below the community's threshold of quality. You may see it by logging in.

Replies are listed 'Best First'.
Re: factorialmath.
by BooK (Curate) on Jun 24, 2002 at 13:17 UTC

Let the effort be in explaining this code, if the AM ever uses it.

```#!/usr/bin/perl
# There is everything you need:
# a sentinel,
\$f{0} = sub { 1 };
# a recursive function,
sub f {
\$f{\$n = pop()-1} ||= sub { f(\$n) };
(\$n+1) * \$f{\$n}->();
}
# a call to the recursive function...
print f(shift);

I hope it doesn't need to pass -w and use strict... ;-) And what did he mean, test if the parameter is a number?!

Student: Umm, well see it has something called a sub, and when you "pop" it it pulls the number and . . .

Professor: F-

indistinguishable from doubletalk.

Re: Factorial Problem
by tadman (Prior) on Jun 24, 2002 at 18:05 UTC
Since this clearly isn't homework (cough), here's an idea of how to solve the problem:
```#!/usr/bin/perl

package F;sub TIESCALAR{bless[],pop}
sub FETCH{\$v=\$n=pop()->[\$|];\$v*=--\$n
while(1<\$n);\$v}sub STORE{shift()->[0
]=pop}tie(\$f,F);\$f=pop;print\$f,\$/,\$@