The factorial of a non-negative number (denoted by ) is the product of all the positive integers less than or equal to that number .
Mathematically, it can be represented by the expression:
Example: The factorial of 6 is .
In order to calculate the factorial of a number in Java, use the following methods.
= n × ()
The recursive program to calculate a factorial is as follows:
class Factorial {public static int factorial(int n) {if (n < 0)throw new IllegalArgumentException("argument should be > 0");return n == 0 ? 1 : n * factorial(n-1);}public static void main( String args[] ) {System.out.println("0! -> " + factorial(0));System.out.println("1! -> " + factorial(1));System.out.println("3! -> " + factorial(3));System.out.println("5! -> " + factorial(5));System.out.println("10! -> " + factorial(10));System.out.println("-1! -> " + factorial(-1));}}
Note that the recursive algorithm factorial calculates (where is a positive integer).
So, if you want to calculate the factorial of -1
as in the last example, then this method will throw an exception because the factorial of negative numbers is not defined.
public class Factorial {public static int factorial(int n) {if (n < 0)throw new IllegalArgumentException("argument should be >0");int result = 1;for(int i = n; i > 1; i--) {result *= i;}return result;}public static void main(String[] args) {System.out.println("0! -> " + factorial(0));System.out.println("1! -> " + factorial(1));System.out.println("3! -> " + factorial(3));System.out.println("5! -> " + factorial(5));System.out.println("10! -> " + factorial(10));System.out.println("-1! -> " + factorial(-1));}}
In the above code, we use a for
loop to calculate the factorial of the number which runs from the current number down until 1
, each number being multiplied with the result.