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 a 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 ans = 1;
        for (int i = 1; i <= n; i++)
           ans = ans * i;
        return ans;
    }

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

}


Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.
Last updated: Wed Feb 9 09:05:37 EST 2011.