tags:

views:

899

answers:

6

I didn't find it, yet. Did I miss something? I know a factorial method is a common example programm for beginners. But wouldn't it be usefull to have a standard implementation for this one to reuse? I could use such a method with standard types (int, long...) and with BigInteger / BigDecimal, too.

+6  A: 

Although factorials make a nice exercise for the beginning programmer, they're not very useful in most cases, and everyone knows how to write a factorial function, so they're typically not in the average library.

bdonlan
I agree with you, there are more important mathematical functions. But in my eyes this method should be standard so that people can reuse it. There is no need to implement it multiple times by multiple people. For educational purposes thay may do. But for every day work it is obsolete. This is my opinion.Anyway, thanks for answering. I will do it on my own - another time.
What is the benefit of your proposed standardization? Adding methods to the standard library is not without costs. As others have pointed out, there is not a single *best* solution. Which one do you propose building into the language? Having a method in the standard library isn't going to save you the time of understanding your problem, and once you've done that you might as well select the implementation that's best suited for the job.
Matt G
+3  A: 

I don't think it would be useful to have a library function for factorial. There is a good deal of research into efficient factorial implementations. Here is a handful of implementations.

Karl the Pagan
+4  A: 

Bare naked factorials are rarely needed in practice. Most often you will need one of the following:

1) divide one factorial by another, or

2) approximated floating-point answer.

In both cases, you'd be better with simple custom solutions.

In case (1), say, if x = 90! / 85!, then you'll calculate the result just as x = 86 * 87 * 88 * 89 * 90, without a need to hold 90! in memory :)

In case (2), google for "Stirling's approximation".

Igor Krivokon
A: 

The only business use for a factorial that I can think of is the Erlang B and Erlang C formulas, and not everyone works in a call center or for the phone company. A feature's usefulness for business seems to often dictate what shows up in a language - look at all the data handling, XML, and web functions in the major languages.

It is easy to keep a factorial snippet or library function for something like this around.

R Ubben
+4  A: 

Apache Commons Math has a few factorial methods in the MathUtils class.

Bill the Lizard
Yep. Good stuff. There is an implementation of factorial for float and non-flat numbers (MathUtils.factorial(int) and MathUtils.factorialDouble(int)) and also useful natural logarithm of n! (MathUtils.factorialLog(int))
pregzt
+1  A: 

Apache Commons Math package has a factorial method, I think you could use that.

Valentin Rocher