Java Factorial factorial(int n)

Here you can find the source of factorial(int n)

Description

Utility method for computing the factorial n!

License

Apache License

Parameter

Parameter Description
n The integer number of which to compute the factorial.

Return

The factorial number n!.

Declaration

public static long factorial(int n) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**//from  w  ww  . j  a v a 2  s.c om
     * Utility method for computing the factorial n! of a number n. NOTE: the
     * resulting factorial is only valid in the scope of the primitive type
     * 'long', so the largest factorial is 20!.
     *
     * @param n The integer number of which to compute the factorial.
     * @return The factorial number n!.
     */
    public static long factorial(int n) {
        // check that we have a number we can actually calculate the factorial for.
        if (n < 0 || n > 20) {
            throw new IllegalArgumentException(
                    "The factorial can only " + "be calculated for numbers n with 0 <= n <= 20 (currently n = " + n
                            + "). Please try to consider less modifications.");
        }
        // handle the trivial cases
        if (n == 0 || n == 1) {
            return 1;
        }
        // calculate the factorial
        long f = 1;
        for (int i = 2; i <= n; i++) {
            f *= i;
        }
        return f;
    }
}

Related

  1. factorial(int input)
  2. factorial(int integer)
  3. factorial(int n)
  4. factorial(int n)
  5. factorial(int n)
  6. factorial(int n)
  7. factorial(int n)
  8. factorial(int n)
  9. factorial(int n)