How to implement factorial in Java

Factorial of an integer above zero is the product of all the integers that have a value less or equal to that value.

Factorial of 3 is 3 times 2 times 1 or 6. In mathematical notation: 3! = 3 * 2 * 1 = 6. The implementation of the method does the same process, it starts at the current value and multiply it with the value minus one. The process is done until the current value is 2. There is no need to multiply by one the result to return.

Create the following java file:

public class Factorial {

    public static long factorial(int number) {
        long result = 1;

        for (int factor = number; factor >= 2; factor--) {
            result *= factor;
        }

        return result;
    }
    
    public static void main(String[] argv) {

	int[] tab = {0,1,2,3,4,5,6,7,8,9};
	for(int i : tab){
	    long out = factorial( i );
	    System.out.println("n = "+  i + "  n! = " + out);
	}
    }

}


This example creates a table with all the integers from 0 to 9. It loops on all of them and calls the factorial method. The result of the method is then written in the output. For example factorial of 6 is 720.

The output will be:

n = 0  n! = 1
n = 1  n! = 1
n = 2  n! = 2
n = 3  n! = 6
n = 4  n! = 24
n = 5  n! = 120
n = 6  n! = 720
n = 7  n! = 5040
n = 8  n! = 40320
n = 9  n! = 362880

References:

Factorial Wikipedia

Recent Comments