factorial : Java Glossary

factorial
Factorial is product of an integer and all smaller integers. It is denoted with an exclamation mark, e. g. 4! is 4 * 3 * 2 * 1 = 24.

Factorial methods are often written recursively just to show off. Iterative coding with a pedestrian for loop is much faster. Mathematicians like to use a powerful theorem proving technique called induction that works much like recursion, so they are enamoured of it and tend to recursion in Java where it is not warranted.

Recursive Calculation

Iterative Calculation

Table Lookup

Since you can’t fit n! into a long for n>20, you might as well use table lookup for a very fast factorial:

Stirling Approximation

Unfortunately, you can only calculate factorial of integers 20 or smaller, even with long arithmetic. To handle bigger ones you must use Stirling’s approximation or a Gamma function.
For hints on faster algorithms you might use to calculate large factorials see Peter’s Math Pages.

Factorials 1 to 30

1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000
17! = 355687428096000
18! = 6402373705728000
19! = 121645100408832000
20! = 2432902008176640000
21! = 51090942171709440000
22! = 1124000727777607680000
23! = 25852016738884976640000
24! = 620448401733239439360000
25! = 15511210043330985984000000
26! = 403291461126605635584000000
27! = 10888869450418352160768000000
28! = 304888344611713860501504000000
29! = 8841761993739701954543616000000
30! = 265252859812191058636308480000000

CMP homejump to top

available on the web at:

http://mindprod.com/jgloss/factorial.html
  

optional Replicator mirror
of mindprod.com
on local hard disk J:

J:\mindprod\jgloss\factorial.html
logo
Please email your , letters to the editor, errors, omissions, typos, formatting errors, ambiguities, unclear wording, broken/redirected link reports, suggestions to improve this page or comments to Roedy Green : feedback email. If you want your message, your name or email kept confidential, not considered for public posting, please explicitly specify that. Unless you state otherwise, I will treat your message as a letter to the editor that I may or may not publish in the feedback section. After that, it will be too late to retract it. If you disagree with something I said, especially when sending an ad-hominem attack, a rant composed mainly of obscenities or a death threat, please quote the offending passage and cite the web page where you found it, tell me why you think it is wrong, and, if possible, provide some supporting evidence. I can’t very well fix erroneous or ambiguous text if I can’t find it.
Blog
IP:[65.110.21.43]
Your face IP:[54.235.20.17]
You are visitor number 23,484.