Last updated 2004-06-28 by Roedy
Green ©1996-2004 Canadian Mind Products
Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
You are here : home : Java Glossary : F words : factorial.
/** calculate n factorial. Only good for 0 <= n <= 20 * @author Roedy Green email */ static long factorial (int n ) { if ( n < 0 || n > 20 ) { throw new IllegalArgumentException( "factorial can only handle 0 <= n <= 20" ); } if ( n == 0 ) { return 1; } long result = n; for ( int i=n-1; i>1; i-- ) { result *= i; } return result; }
Since you can't fit n! into a long for n>20, you might as well use table lookup for a very fast factorial:
Unfortunately, you can only calculate factorial of integers 20 or smaller, even with long arithmetic. To handle bigger ones you must use Sterling's approximation or a Gamma function.
For hints on faster algorithms you might use to calculate large factorials see Peter's Math Pages.
home |
Canadian Mind Products | |||
| mindprod.com IP:[24.87.56.253] | ||||
| Your IP:[80.134.30.163] | ||||
| You are visitor number 3005. | ||||
| Please send errors, omissions and suggestions | ||||
| to improve this page to Roedy Green. | ||||
| You can get a fresh copy of this page from: | or possibly from your local J: drive mirror: | |||
| http://mindprod.com/jgloss/factorial.html | J:\mindprod\jgloss\factorial.html | |||