I didn't find it, yet. Did I miss something? I know a factorial method is a common example program for beginners. But wouldn't it be useful to have a standard implementation for this one to reuse? I could use such a method with standard types (Eg. int, long...) and with BigInteger / BigDecimal, too.
30 Answers
Apache Commons Math has a few factorial methods in the MathUtils class.

- 41,764
- 65
- 238
- 329

- 398,270
- 210
- 566
- 880
-
1Yep. 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)) – Tomasz Błachowicz May 21 '09 at 09:01
-
3it's in ArithmeticUtils at the moment. – MarianP Oct 16 '13 at 11:13
-
6ArithmeticUtils.factorial is appearently deprecated now, atm use [CombinatoricsUtils.factorial](https://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/CombinatoricsUtils.html#factorial(int)) – Victor Häggqvist May 23 '14 at 16:22
-
1Please don't use links! They tend to disappear (like ALL of these have). – SMBiggs Mar 13 '20 at 22:12
-
1@ScottBiggs Both of the links in the answer are working fine. – Bill the Lizard Mar 14 '20 at 13:43
-
@BilltheLizard So they are. Must've been a fluke last night. – SMBiggs Mar 15 '20 at 03:03
-
The ```org.apache.commons.math4.util.MathUtils``` is not released and under development, do you guys build the jar from source code and then add the library manually becoz the latest release ```org.apache.commons.math3.util.MathUtils``` does not have factorial method – akram Aug 29 '20 at 18:20
public class UsefulMethods {
public static long factorial(int number) {
long result = 1;
for (int factor = 2; factor <= number; factor++) {
result *= factor;
}
return result;
}
}
Big Numbers version by HoldOffHunger:
public static BigInteger factorial(BigInteger number) {
BigInteger result = BigInteger.valueOf(1);
for (long factor = 2; factor <= number.longValue(); factor++) {
result = result.multiply(BigInteger.valueOf(factor));
}
return result;
}

- 3,552
- 2
- 22
- 28

- 461
- 4
- 2
-
-
-
2Big Numbers Version: public static BigInteger factorial(BigInteger n) { BigInteger factorial = BigInteger.valueOf(1); for (int i = 1; i <= n.intValue(); i++) { factorial = factorial.multiply(BigInteger.valueOf(i)); } return factorial; } – HoldOffHunger Sep 27 '16 at 23:31
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.

- 1,944
- 17
- 17
-
210
-
20Not many people actually need factorials in real code. If you do, then you are probably doing some advanced maths or statistics, in which case you will already most likely be using a maths library with a specialised factorial implementation. – mikera Jul 20 '13 at 09:04
-
3The gamma function is very useful, which is why it's included in the C++ standard library. – Columbo Sep 01 '16 at 17:46
-
2Sounds to me that @KarlthePagan means it's not useful to have a _standard_ library function for factorial -- is that correct? – dantiston Jan 25 '17 at 03:17
-
1so they would ask you at the interview to see if you can do it yourself *my case – moldovean Jun 25 '17 at 15:45
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".

- 10,145
- 1
- 37
- 41
-
3Counterexample: Calculating the number of permutations with N elements requires bare factorial, and is needed if you want to allocate a structure to hold the permutations. – Mark Jeronimus Jan 01 '16 at 17:46
-
Good point! My first question was if 90!/85! simplified down because of a common denominator of 5, but actually, it was the common denominator of 85!. 90!/85! = 90*89*88*87*86*85!/85!. You can see it more clearly in that equality. – HoldOffHunger Sep 27 '16 at 23:34
Use Guava's BigIntegerMath
as follows:
BigInteger factorial = BigIntegerMath.factorial(n);
(Similar functionality for int
and long
is available in IntMath
and LongMath
respectively.)

- 266,786
- 75
- 396
- 414
Short answer is: use recursion.
You can create one method and call that method right inside the same method recursively:
public class factorial {
public static void main(String[] args) {
System.out.println(calc(10));
}
public static long calc(long n) {
if (n <= 1)
return 1;
else
return n * calc(n - 1);
}
}
-
5recursively functions are nice, but if someone will try count a really big fatiorial, they will end up with StackOverflowException ;) + Im not sure, but i think recursion is slower than good old loop method ;) – T.G Apr 05 '14 at 13:47
-
-
2That is simple. each recursively is putting current place on stack so program will have 'memory' of place to go back to after method call is finish. Stack have its limits. to try it for yourself try in code above change `System.out.println(calc(10));` to `System.out.println(calc(Long.MAX_VALUE));` you should get pretty long stactrace :) – T.G Jan 23 '17 at 16:59
-
1@TG To be clear I tried [my recursive method](https://stackoverflow.com/a/54392952/7721600) which is working with `BigInteger`. I tried to calculate the factorial of the number `8020` which gave me the result `613578884952214809325384...` which has `27831` decimal places. So even when working with numbers that huge no `Stackoverflow` will be thrown. Ofcourse youre right but I doubt there are numbers that big with a practial use :-) – Moritz Schmidt Jan 27 '19 at 21:33
i believe this would be the fastest way, by a lookup table:
private static final long[] FACTORIAL_TABLE = initFactorialTable();
private static long[] initFactorialTable() {
final long[] factorialTable = new long[21];
factorialTable[0] = 1;
for (int i=1; i<factorialTable.length; i++)
factorialTable[i] = factorialTable[i-1] * i;
return factorialTable;
}
/**
* Actually, even for {@code long}, it works only until 20 inclusively.
*/
public static long factorial(final int n) {
if ((n < 0) || (n > 20))
throw new OutOfRangeException("n", 0, 20);
return FACTORIAL_TABLE[n];
}
For the native type long
(8 bytes), it can only hold up to 20!
20! = 2432902008176640000(10) = 0x 21C3 677C 82B4 0000
Obviously, 21!
will cause overflow.
Therefore, for native type long
, only a maximum of 20!
is allowed, meaningful, and correct.

- 5,157
- 7
- 38
- 52
-
1Quite nice idea. considering, that factorial first 20 is probably enough, i would add a static constants (no need to calculate it every time app launch) to Math class with those data provided. Fact that not many people needs factorials in their code is a poor excuse to not support it in Math class. – T.G Apr 05 '14 at 13:53
Because factorial grows so quickly, stack overflow is not an issue if you use recursion. In fact, the value of 20! is the largest one can represent in a Java long. So the following method will either calculate factorial(n) or throw an IllegalArgumentException if n is too big.
public long factorial(int n) {
if (n > 20) throw new IllegalArgumentException(n + " is out of range");
return (1 > n) ? 1 : n * factorial(n - 1);
}
Another (cooler) way to do the same stuff is to use Java 8's stream library like this:
public long factorial(int n) {
if (n > 20) throw new IllegalArgumentException(n + " is out of range");
return LongStream.rangeClosed(1, n).reduce(1, (a, b) -> a * b);
}
Read more on Factorials using Java 8's streams

- 290
- 2
- 7
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.

- 224,562
- 31
- 268
- 324
-
6I 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. – May 21 '09 at 01:52
-
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 May 21 '09 at 02:24
-
2"...and everyone knows how to write a factorial function" http://chaosinmotion.com/blog/?p=622 – James P. Apr 03 '13 at 00:22
-
4Disagree. Factorials are required for [Combinatorics](http://en.wikipedia.org/wiki/Combinatorics), which is needed in many areas of software design. The argument not include factorials in a built-in maths library is the same argument as not having a built-in maths library. – LateralFractal Sep 27 '13 at 23:54
-
What an outstanding piece of logic. Absolutely stellar. Too bad the java.lang.Math class designers were ignorant of it when they included the abs() methods into that lib. – Igor Soudakevitch Jan 24 '20 at 08:52
Apache Commons Math package has a factorial method, I think you could use that.

- 275,237
- 103
- 548
- 598

- 11,667
- 45
- 59
-
The updated link is [this](http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/ArithmeticUtils.html#factorial(int)) – Marco Lackovic May 01 '13 at 21:21
-
Try this
public static BigInteger factorial(int value){
if(value < 0){
throw new IllegalArgumentException("Value must be positive");
}
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= value; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}

- 31,250
- 24
- 137
- 216
-
3I believe there is a bug in the for-loop: it should be `i <= value`. The for-loop could be slightly optimized to `(int i = 2; i <= value; i++)`. – Chris Apr 23 '15 at 20:22
You can use recursion.
public static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
and then after you create the method(function) above:
System.out.println(factorial(number of your choice));
//direct example
System.out.println(factorial(3));

- 1,455
- 14
- 19
I found an amazing trick to find factorials in just half the actual multiplications.
Please be patient as this is a little bit of a long post.
For Even Numbers: To halve the multiplication with even numbers, you will end up with n/2 factors. The first factor will be the number you are taking the factorial of, then the next will be that number plus that number minus two. The next number will be the previous number plus the lasted added number minus two. You are done when the last number you added was two (i.e. 2). That probably didn't make much sense, so let me give you an example.
8! = 8 * (8 + 6 = 14) * (14 + 4 = 18) * (18 + 2 = 20)
8! = 8 * 14 * 18 * 20 which is **40320**
Note that I started with 8, then the first number I added was 6, then 4, then 2, each number added being two less then the number added before it. This method is equivalent to multiplying the least numbers with the greatest numbers, just with less multiplication, like so:
8! = 1 * 2 * 3 * 4 * 5 * 6 * 7 *
8! = (1 * 8) * (2 * 7) * (3 * 6) * (4 * 5)
8! = 8 * 14 * 18 * 20
Simple isn't it :)
Now For Odd Numbers: If the number is odd, the adding is the same, as in you subtract two each time, but you stop at three. The number of factors however changes. If you divide the number by two, you will end up with some number ending in .5. The reason is that if we multiply the ends together, that we are left with the middle number. Basically, this can all be solved by solving for a number of factors equal to the number divided by two, rounded up. This probably didn't make much sense either to minds without a mathematical background, so let me do an example:
9! = 9 * (9 + 7 = 16) * (16 + 5 = 21) * (21 + 3 = 24) * (roundUp(9/2) = 5)
9! = 9 * 16 * 21 * 24 * 5 = **362880**
Note: If you don't like this method, you could also just take the factorial of the even number before the odd (eight in this case) and multiply it by the odd number (i.e. 9! = 8! * 9).
Now let's implement it in Java:
public static int getFactorial(int num)
{
int factorial=1;
int diffrennceFromActualNum=0;
int previousSum=num;
if(num==0) //Returning 1 as factorial if number is 0
return 1;
if(num%2==0)// Checking if Number is odd or even
{
while(num-diffrennceFromActualNum>=2)
{
if(!isFirst)
{
previousSum=previousSum+(num-diffrennceFromActualNum);
}
isFirst=false;
factorial*=previousSum;
diffrennceFromActualNum+=2;
}
}
else // In Odd Case (Number * getFactorial(Number-1))
{
factorial=num*getFactorial(num-1);
}
return factorial;
}
isFirst
is a boolean variable declared as static; it is used for the 1st case where we do not want to change the previous sum.
Try with even as well as for odd numbers.

- 2,237
- 27
- 30
- 38

- 7,643
- 6
- 34
- 62
A very simple method to calculate factorials:
private double FACT(double n) {
double num = n;
double total = 1;
if(num != 0 | num != 1){
total = num;
}else if(num == 1 | num == 0){
total = 1;
}
double num2;
while(num > 1){
num2 = num - 1;
total = total * num2;
num = num - 1;
}
return total;
}
I have used double because they can hold massive numbers, but you can use any other type like int, long, float, etc.
P.S. This might not be the best solution but I am new to coding and it took me ages to find a simple code that could calculate factorials so I had to write the method myself but I am putting this on here so it helps other people like me.

- 464
- 5
- 11
You can use recursion version as well.
static int myFactorial(int i) {
if(i == 1)
return;
else
System.out.prinln(i * (myFactorial(--i)));
}
Recursion is usually less efficient because of having to push and pop recursions, so iteration is quicker. On the other hand, recursive versions use fewer or no local variables which is advantage.

- 52,260
- 74
- 224
- 365
Factorial is highly increasing discrete function.So I think using BigInteger is better than using int. I have implemented following code for calculation of factorial of non-negative integers.I have used recursion in place of using a loop.
public BigInteger factorial(BigInteger x){
if(x.compareTo(new BigInteger("1"))==0||x.compareTo(new BigInteger("0"))==0)
return new BigInteger("1");
else return x.multiply(factorial(x.subtract(new BigInteger("1"))));
}
Here the range of big integer is
-2^Integer.MAX_VALUE (exclusive) to +2^Integer.MAX_VALUE,
where Integer.MAX_VALUE=2^31.
However the range of the factorial method given above can be extended up to twice by using unsigned BigInteger.

- 5,171
- 3
- 23
- 40
We need to implement iteratively. If we implement recursively, it will causes StackOverflow if input becomes very big (i.e. 2 billions). And we need to use unbound size number such as BigInteger to avoid an arithmatic overflow when a factorial number becomes bigger than maximum number of a given type (i.e. 2 billion for int). You can use int for maximum 14 of factorial and long for maximum 20 of factorial before the overflow.
public BigInteger getFactorialIteratively(BigInteger input) {
if (input.compareTo(BigInteger.ZERO) <= 0) {
throw new IllegalArgumentException("zero or negatives are not allowed");
}
BigInteger result = BigInteger.ONE;
for (BigInteger i = BigInteger.ONE; i.compareTo(input) <= 0; i = i.add(BigInteger.ONE)) {
result = result.multiply(i);
}
return result;
}
If you can't use BigInteger, add an error checking.
public long getFactorialIteratively(long input) {
if (input <= 0) {
throw new IllegalArgumentException("zero or negatives are not allowed");
} else if (input == 1) {
return 1;
}
long prev = 1;
long result = 0;
for (long i = 2; i <= input; i++) {
result = prev * i;
if (result / prev != i) { // check if result holds the definition of factorial
// arithmatic overflow, error out
throw new RuntimeException("value "+i+" is too big to calculate a factorial, prev:"+prev+", current:"+result);
}
prev = result;
}
return result;
}

- 191
- 6
We have a single line to calculate it:
Long factorialNumber = LongStream.rangeClosed(2, N).reduce(1, Math::multiplyExact);

- 6,749
- 16
- 58
- 100
/**
import java liberary class
*/
import java.util.Scanner;
/* class to find factorial of a number
*/
public class factorial
{
public static void main(String[] args)
{
// scanner method for read keayboard values
Scanner factor= new Scanner(System.in);
int n;
double total = 1;
double sum= 1;
System.out.println("\nPlease enter an integer: ");
n = factor.nextInt();
// evaluvate the integer is greater than zero and calculate factorial
if(n==0)
{
System.out.println(" Factorial of 0 is 1");
}
else if (n>0)
{
System.out.println("\nThe factorial of " + n + " is " );
System.out.print(n);
for(int i=1;i<n;i++)
{
do // do while loop for display each integer in the factorial
{
System.out.print("*"+(n-i) );
}
while ( n == 1);
total = total * i;
}
// calculate factorial
sum= total * n;
// display sum of factorial
System.out.println("\n\nThe "+ n +" Factorial is : "+" "+ sum);
}
// display invalid entry, if enter a value less than zero
else
{
System.out.println("\nInvalid entry!!");
}System.exit(0);
}
}

- 11
- 2
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.

- 2,225
- 16
- 8
public static int fact(int i){
if(i==0)
return 0;
if(i>1){
i = i * fact(--i);
}
return i;
}
-
1I think the OP is asking if there is a function in the API's, not how to write one. Also, 0! = 1 - you may wish to update your code to include that case. – S.L. Barth is on codidact.com Mar 12 '14 at 14:33
public int factorial(int num) {
if (num == 1) return 1;
return num * factorial(num - 1);
}

- 8,341
- 6
- 31
- 38
while loop (for small numbers)
public class factorial {
public static void main(String[] args) {
int counter=1, sum=1;
while (counter<=10) {
sum=sum*counter;
counter++;
}
System.out.println("Factorial of 10 is " +sum);
}
}

- 1,235
- 10
- 26
I got this from EDX use it! its called recursion
public static int factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n-1);
}
}

- 22,364
- 14
- 59
- 168

- 23
- 4
with recursion:
public static int factorial(int n)
{
if(n == 1)
{
return 1;
}
return n * factorial(n-1);
}
with while loop:
public static int factorial1(int n)
{
int fact=1;
while(n>=1)
{
fact=fact*n;
n--;
}
return fact;
}

- 1,916
- 6
- 27
- 36
using recursion is the simplest method. if we want to find the factorial of N, we have to consider the two cases where N = 1 and N>1 since in factorial we keep multiplying N,N-1, N-2,,,,, until 1. if we go to N= 0 we will get 0 for the answer. in order to stop the factorial reaching zero, the following recursive method is used. Inside the factorial function,while N>1, the return value is multiplied with another initiation of the factorial function. this will keep the code recursively calling the factorial() until it reaches the N= 1. for the N=1 case, it returns N(=1) itself and all the previously built up result of multiplied return N s gets multiplied with N=1. Thus gives the factorial result.
static int factorial(int N) {
if(N > 1) {
return n * factorial(N - 1);
}
// Base Case N = 1
else {
return N;
}

- 12,336
- 9
- 27
- 49

- 21
- 2
public static long factorial(int number) {
if (number < 0) {
throw new ArithmeticException(number + " is negative");
}
long fact = 1;
for (int i = 1; i <= number; ++i) {
fact *= i;
}
return fact;
}
using recursion.
public static long factorial(int number) {
if (number < 0) {
throw new ArithmeticException(number + " is negative");
}
return number == 0 || number == 1 ? 1 : number * factorial(number - 1);
}

- 3,863
- 1
- 25
- 16
Using Java 9+, you can use this solution. This uses BigInteger, ideal for holding large numbers.
...
import java.math.BigInteger;
import java.util.stream.Stream;
...
String getFactorial(int n) {
return Stream.iterate(BigInteger.ONE, i -> i.add(BigInteger.ONE)).parallel()
.limit(n).reduce(BigInteger.ONE, BigInteger::multiply).toString();
}

- 79
- 6
USING DYNAMIC PROGRAMMING IS EFFICIENT
if you want to use it to calculate again and again (like caching)
Java code:
int fact[]=new int[n+1]; //n is the required number you want to find factorial for.
int factorial(int num)
{
if(num==0){
fact[num]=1;
return fact[num];
}
else
fact[num]=(num)*factorial(num-1);
return fact[num];
}

- 1,160
- 1
- 12
- 23