Class Factorials

java.lang.Object
edu.cnm.deepdive.Factorials

public final class Factorials extends Object
Implements recursive and iterative forms of factorial computation, returning long and BigInteger results. (When n > 20, n! exceeds the range of values that can be represented by the long type.)

Note that for large values of n, the computation of n! is best done by methods other than those included here.

  • Method Details

    • longRecursive

      public static long longRecursive(int n) throws IllegalArgumentException
      Computes (recursively) and returns n! as a long. However, if (n > 20), the result overflows the range of long, and is meaningless.
      Parameters:
      n - Value for which factorial is computed.
      Returns:
      Factorial of n; that is, n!.
      Throws:
      IllegalArgumentException - If (n < 0) or (n > 20).
    • longIterative

      public static long longIterative(int n) throws IllegalArgumentException
      Computes (iteratively) and returns n! as a long. However, if (n > 20), the result overflows the range of long, and is meaningless.
      Parameters:
      n - Value for which factorial is computed.
      Returns:
      Factorial of n; that is, n!.
      Throws:
      IllegalArgumentException - If (n < 0) or (n > 20).
    • bigRecursive

      public static BigInteger bigRecursive(int n) throws IllegalArgumentException
      Computes (recursively) and returns the factorial of n as a BigInteger.
      Parameters:
      n - Value for which factorial is computed.
      Returns:
      Factorial of n; that is, n!.
      Throws:
      IllegalArgumentException - If (n < 0).
    • bigIterative

      public static BigInteger bigIterative(int n) throws IllegalArgumentException
      Computes (recursively) and returns the factorial of n as a BigInteger.
      Parameters:
      n - Value for which factorial is computed.
      Returns:
      Factorial of n; that is, n!.
      Throws:
      IllegalArgumentException - If (n < 0).