/* * T12n01.java: Two methods that compute n! -- one iterative, the other * recursive. Note that the methods use the 'long' type instead of the * 'int' type. This allows for larger integers to be stored. Even so, * the factorial function grows so fast that we can only compute 20!. * If you need to compute even larger factorials, you'll want to use * Java's BigInteger class. */ import java.util.*; public class T12n01 { /* * factorialIterative(n) -- Computes n! iteratively and returns it. * * Precondition: n is a non-negative integer <= 20 * Postcondition: n! is returned */ public static long factorialIterative(long n) { long product = 1; // running product of integer sequence if (n == 0) // Special case of 0! = 1 (but is this needed?) return 1; else { // General case of n! = 2 * ... * (n-1) * n for (int i = 2; i <= n; i++) { product *= i; } return product; } } /* * factorialRecursive(n) -- Computes n! recursively and returns it. * * Precondition: n is a non-negative integer <= 20 * Postcondition: n! is returned */ public static long factorialRecursive(long n) { if (n == 0) // Base case of 0! = 1 (again, is this needed?) return 1; else // General case of n! = n * (n-1)! return n * factorialRecursive(n-1); } public static void main (String [] args) { if (args.length < 1) { System.out.println("\n\tUSAGE: java T12n01 and |n|! will " + "be displayed if |n| <= 20.\n"); System.exit(1); } long n = Math.abs(Long.parseLong(args[0])); if (n <= 20) { System.out.println("Iteratively, " + n + "! = " + factorialIterative(n)); System.out.println("Recursively, " + n + "! = " + factorialRecursive(n)); } else { System.out.println("A Java long cannot hold 21! or larger."); } } }