Easy Tutorial
❮ Collection Minmax Dir Parent ❯

Java Example - Factorial

Java Examples

The factorial of a positive integer (English: factorial) is the product of all positive integers less than or equal to that number, and the factorial of 0 is defined as 1. The factorial of a natural number n is written as n!.

That is, n! = 1 × 2 × 3 × ... × n. The factorial can also be defined recursively: 0! = 1, n! = (n-1)! × n.

The following example demonstrates the implementation of the factorial code in Java:

MainClass.java File

public class MainClass {
    public static void main(String args[]) {
        for (int counter = 0; counter <= 10; counter++){
            System.out.printf("%d! = %d\n", counter, factorial(counter));
        }
    }
    public static long factorial(long number) {
        if (number <= 1)
            return 1;
        else
            return number * factorial(number - 1);
    }
}

The above code outputs the following results:

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

Java Examples

❮ Collection Minmax Dir Parent ❯