Writing a Factorial Subroutine in Perl

Perl seems to lack a native factorial function. Here is a simple subroutine that does the job.

1
2
3
4
5
sub factorial {
	my $n = 1;
	$n *= $_ for 2..shift;
	return $n;
}

The script is pretty straight-forward, except the third line. Expanding it to a more eligible block, we would get:

1
2
3
4
5
6
7
8
sub factorial {
	my $n = 1;
	my $max = shift; # multiply all numbers up to this
	for my $i (2..$max) { # for all numbers between 2 and $max,
		$n *= $i # multiply them together
	}
	return $n;
}

If you want, for example, 64! (64 factorial), you just call &factorial(64). This seems to work fine for all integers up to 171, which Perl equals to infinity.

Maybe Related?

6 Comments »

  1. Hi Tim, You seem to be fairly proficient in Perl.. Can you tell me where are some good resources for learning Perl? Thanks!

    Comment by Sameer Sontakey — July 19, 2007 @ 7:44 pm

  2. Sameer, perlintro of perldoc is a good start, and after that, there is lots of information in those pages. Also, reading obfuscation contests actually help in understanding the semantics of the language.

    Comment by Tim — July 20, 2007 @ 9:01 am

  3. Thanks! I will check that site out. By the way, what is your favorite programming language?

    Comment by Sameer Sontakey — July 21, 2007 @ 12:12 am

  4. Sameer: Perl, no doubt :)

    Comment by Tim — July 23, 2007 @ 10:08 pm

  5. Software Development Guide…

    I couldn’t understand some parts of this article, but it sounds interesting…

    Trackback by Software Development Guide — October 16, 2007 @ 8:39 pm

  6. To count factorials greater than 171 you shoul use some kind of external C library. I myself prefer Math::PARI (did some extensive benchmarking on GMP vs PARI, and the latter won :) ).

    Comment by alpha — March 23, 2008 @ 2:07 am

RSS feed for comments on this post. TrackBack URI

Leave a comment

FireStats iconAnvänder FireStats