In mathematics, the factorial of a positive integer **n** denoted by **n!,** is the product of all positive integers **less than or equal to n**. For example,

5 ! = 1 x 2 x 3 x times 4 x 5 = 120

0! is a special case that is explicitly defined to be 1.

The factorial operation is encountered in many different areas of mathematics, notably in combinatorics, algebra and mathematical analysis. Its most basic occurrence is the fact that there are **n! **ways to arrange n distinct objects into a sequence (i.e., permutations of a the set of objects).

This fact was known at least as early as the 12-th century, to Hindu scholars. The notation **n!** was introduced by Christian Kramp in 1808. – From Wikipedia.

## Factorial Flowchart

The following flowchart shows how to compute the factorial of a number.

## Factorial Program

The following Java snippet shows how to compute the factorial of any number.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
package com.livrona.snippets.numbers; /** * A simple practice snippet the computes the factorial of a given input number. * * @author java4learners * */ public class ComputeFactorial { /** * Test Method * * @param args */ public static void main(String[] args) { if (args.length != 1) { System.out .println("Usage: java com.livrona.snippets.numbers.ComputeFactorial <factorial of>"); System.exit(0); } // store args String factorialOf = args[0]; System.out.println("Factorial of : " + factorialOf); // invoke the method try { System.out.println("is :" + factorial(new Integer(factorialOf).intValue())); } catch (Exception e) { System.out.println("Failed to compute the Factorial: " + e.getMessage()); e.printStackTrace(); } } /** * Computes the Factorial of a given number * * @param n * @return */ public static long factorial(int n) { long fact = 1; // loop through 1 to till number and multiple for (int i = 1; i <= n; i++) { fact = fact * i; } return fact; } } |

## Program Output

The following is the output of the above program for **when the input is 5. i.e. **computing the factorial of 5.

Factorial of : 5

is :120

[pb_builder]