The moose likes Java in General and the fly likes factorial Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "factorial" Watch "factorial" New topic


James Kerruish

Joined: Aug 22, 2001
Posts: 16
I need to compute the factorial of a set of large numbers. What is the best way to do this? Bearing in mind I need it done as quickly as possible. Should I use the gamma function and if so how do I accomplish this in Java.
[ October 28, 2002: Message edited by: James Kerruish ]
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
If you really needed to do it "as quickly as possible", you should probably program it in assembler, not in Java. But I guess you didn't really mean that, so, what are your actual performance constraints? Are you sure that a simple algorithm wouldn't suffice???

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
A gamma function? I seriously doubt it's useful here - for integer values, it's much simpler to use a straightforward factorial implementation. If that's not good enough, for your situation (calculating factorials for many numbers) it might well be worthwhile to pre-generate a table, something like this:

Of course, you can adjust MAX_INPUT as desired. And I believe BigInteger used to be annoyingly slow, but has since been improved. You may wish to replace BigInteger with a custom class if you're using an older JDK version. And of course, if you're not interested in the factorial of any number larger than 20, you can just use a long rather than BigInteger.
[ October 28, 2002: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: factorial
It's not a secret anymore!