What follows is the highlighted source code with comments. You can also download this file directly: BigFactorial.java.
/* * This work by W. Patrick Hooper is free of known copyright restrictions. * The work is in the public domain. * * Author's website: <a href="http://wphooper.com">http://wphooper.com</a>. */ // This line allows us to use the java.math.BigInteger class // under the name BigInteger. import java.math.BigInteger; /** * Compute n! for arbitrarily large n. */ public class BigFactorial { /** return n factorial. */ public static BigInteger factorial(int n) { // We will compute n factorial via the formula // n!=1*2*3*4*5*... // Construct a big integer with a value of 1. BigInteger factorial=BigInteger.valueOf(1); // iterate over the values i=1,...,n. for (int i=1; i<=n; i++) { // Convert each i to a BigInteger, then multiply factorial by it. factorial=factorial.multiply(BigInteger.valueOf(i)); } return factorial; } /** Print n!, where n is the first command line argument. */ public static void main(String[] args) { int n=Integer.parseInt(args[0]); System.out.println(""+n+"! = "+factorial(n)); } }