Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

factorial

 
James Kerruish
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Thanks
James
[ October 28, 2002: Message edited by: James Kerruish ]
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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???
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic