Factorial.java


Below is the syntax highlighted version of Factorial.java from §2.1 Static Methods.


/******************************************************************************
 *  Compilation:  javac Factorial.java
 *  Execution:    java Factorial 10
 *
 *  Reads in an integer command-line argument n, and prints n! = 1 * 2 * ... * n
 *  to standard output.
 *
 *  % java Factorial 0
 *  1
 *
 *  % java Factorial 3
 *  6
 *
 *  % java Factorial 20
 *  2432902008176640000
 *
 *  % java Factorial 21
 *  -4249290049419214848          // overflow
 *
 ******************************************************************************/

public class Factorial {

    // return n!, assuming n >= 0
    public static long factorial(int n) {
        long product = 1;
        for (int i = 1; i <= n; i++)
            product = product * i;
        return product;
    }

    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        StdOut.println(factorial(n));
    }

}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:15:13 EDT 2022.