JavaDevNotes.com

Factorial Java

In mathematics, factorial of a number means taking the product of all positive integers less than or equal to the given number. Or the product of multiplying all numbers from one to the given number. For example, the factorial of 6 is 1x2x3x4x5x6=720. Factorial has many uses, specifically in combinatorics or counting problems, as this is a building block for coming up with more complex counting formula. However, this also have uses in other branch of mathematics, hence writing program that is math heavy may need to have a way of computing factorial. If you are working with the Java programming language, this post might help. This post will show example on how to compute factorial in Java. We will help write a factorial program in Java.

Factorial Program in Java using Loop

Since the definition of factorial is pretty straightforward, we can use a simple loop to calculate factorial in Java. Below is an example on how to calculate the factorial of 6.

package test;
/**
 * A simple example that computes the factorial of a number.
 */
public class FactorialExample {
    private static int N = 6;
    public static void main(String[] args) {
        long product = 1;
        for(int i = 2; i <= N; i++)
        {
            product = product * i;
        }
        System.out.printf("Factorial of %d is %d", N, product);
    }
}

The above code loops starting from two upto the given number 6 and accumulate the product. We did not start with one on the loop as the value of product is initialized with 1. Multiplying one with one will have no effect and would waste some performance, although minimal. Below is the result of the code.
Factorial of 6 is 720

Factorial Method in Java

When we need to compute factorial multiple times, it is convenient to code it inside a function. The function we write can be invoked multiple times in different places of our program. Below is a simple example on how we could extract the logic above of computing the factorial of a number in Java, into a separate method for reusability.
package test;
/**
 * A simple example that computes the factorial of a number inside a function.
 */
public class FactorialExample {
    private static long factorial(int n) {
        long product = 1;
        for(int i = 2; i <= n; i++)
        {
            product = product * i;
        }
        return product;
    }
    public static void main(String[] args) {
        System.out.printf("Factorial of %d is %d\n", 1, factorial(1));
        System.out.printf("Factorial of %d is %d\n", 2, factorial(2));
        System.out.printf("Factorial of %d is %d\n", 3, factorial(3));
        System.out.printf("Factorial of %d is %d\n", 4, factorial(4));
        System.out.printf("Factorial of %d is %d\n", 5, factorial(5));
    }
}
As shown above, the function is coded very similar to the first example, and just returns the calculated product. We invoked the factorial method using different values, and the output is shown below.
Factorial of 1 is 1
Factorial of 2 is 2
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
Which is the expected result.

Factorial in Java Using BigInteger

One drawback of using primitive data type is it can only hold relatively small value. Maximum value for int type is 2147483647 while max value of long is 9223372036854775807. But what if we want more than that? We can use BigInteger for this case. Below is an example on how to compute the factorial of a number in Java using BigInteger.
package test;
import java.math.BigInteger;
/**
 * A simple example that computes the factorial using BigInteger.
 */
public class FactorialExample {
    private static BigInteger factorial(int n) {
        BigInteger product = BigInteger.ONE;
        for(int i = 2; i <= n; i++)
        {
            product = product.multiply(BigInteger.valueOf(i));
        }
        return product;
    }
    public static void main(String[] args) {
        System.out.printf("Factorial of %d is %d\n", 21, factorial(21));
        System.out.printf("Factorial of %d is %d\n", 22, factorial(22));
        System.out.printf("Factorial of %d is %d\n", 23, factorial(23));
        System.out.printf("Factorial of %d is %d\n", 24, factorial(24));
        System.out.printf("Factorial of %d is %d\n", 25, factorial(25));
    }
}
Our example calculated the facorial of 21, 22, 23, 24, and 25. Where the answers are very large values. Below is the output that shows it far exceeds the capacity of long.
Factorial of 21 is 51090942171709440000
Factorial of 22 is 1124000727777607680000
Factorial of 23 is 25852016738884976640000
Factorial of 24 is 620448401733239439360000
Factorial of 25 is 15511210043330985984000000

Factorial Recursion Java

One of the most elegant way of solving things in Java or other language is by using recursion. It just looks beautiful because it closely resemble the definition of what we are programming. Recursive solution also tend to be shorter and more concise. Below in an example on how to get factorial of a number in Java using recursion.
package test;
/**
 * A simple example that computes the factorial of a number using recursion.
 */
public class FactorialExample {
    private static long factorial(int n) {
        if (n == 1 || n == 2) {
            return n;
        }
        return n * factorial(n - 1);    
    }
    public static void main(String[] args) {
        System.out.printf("Factorial of %d is %d\n", 1, factorial(1));
        System.out.printf("Factorial of %d is %d\n", 2, factorial(2));
        System.out.printf("Factorial of %d is %d\n", 3, factorial(3));
        System.out.printf("Factorial of %d is %d\n", 4, factorial(4));
        System.out.printf("Factorial of %d is %d\n", 5, factorial(5));
    }
}
And as expected, we get the same result as in the previous examples.
Factorial of 1 is 1
Factorial of 2 is 2
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120

Factorial in Java using Java 8 Stream

Since the introduction of Stream in Java 8, new ways of solving problems can be found. Below is an example on how to get the factorial of a number in Java using Stream feature of Java 8.
package test;
import java.util.stream.LongStream;
/**
 * A simple example that computes the factorial of a number using recursion.
 */
public class FactorialExample {
    private static long factorial(int n) {
        return LongStream.rangeClosed(1, n)
                .reduce(1, (long x, long y) -> x * y);    
    }
    public static void main(String[] args) {
        System.out.printf("Factorial of %d is %d\n", 1, factorial(1));
        System.out.printf("Factorial of %d is %d\n", 2, factorial(2));
        System.out.printf("Factorial of %d is %d\n", 3, factorial(3));
        System.out.printf("Factorial of %d is %d\n", 4, factorial(4));
        System.out.printf("Factorial of %d is %d\n", 5, factorial(5));
    }
}

As always, we get the same result when we run the program above.

Factorial of 1 is 1
Factorial of 2 is 2
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120