/*
 * ======================================================================
 * Factorial.java. This program:
 *
 *    1. Computes factorial(x), where x is a positive integer.
 *    2. Demonstrates use of factorial(x) in arithmetic expressions.
 *
 * ----------------------------------------------------------------------
 * Note: The expression factorial(4)*Math.sqrt(4) involves and integer
 *       and a double precision number. Java will store the result as a
 *       double precision floating point number.
 *
 *       To print the result result as an integer, we must cast the
 *       result to data type (int), as in,
 *
 *              (int) (factorial(4)*Math.sqrt(4) + 4)/4);
 *
 * Written by: Mark Austin                                  February 2008
 * ======================================================================
 */

import java.lang.Math;

public class Factorial {

    // =============================================
    // Compute and return iNo !
    // =============================================

    public static int factorial( int iNo ) {

        // Make sure that the input argument is positive

	if (iNo < 0) throw
           new IllegalArgumentException("iNo must be >= 0");

        // Use simple look to compute factorial....

        int factorial = 1;
        for(int i = 2; i <= iNo; i++) 
            factorial *= i;               

        return factorial;
    }

    // =============================================
    // Exercise factorial function ....
    // =============================================

    public static void main ( String args[] ) {

       // Compute and print sample factorial numbers ....

       System.out.printf("Factorial  0! = %10d\n", factorial ( 0) );
       System.out.printf("Factorial  1! = %10d\n", factorial ( 1) );
       System.out.printf("Factorial  2! = %10d\n", factorial ( 2) );
       System.out.printf("Factorial  3! = %10d\n", factorial ( 3) );
       System.out.printf("Factorial  4! = %10d\n", factorial ( 4) );
       System.out.printf("Factorial  5! = %10d\n", factorial ( 5) );
       System.out.printf("Factorial  6! = %10d\n", factorial ( 6) );
       System.out.printf("Factorial  7! = %10d\n", factorial ( 7) );
       System.out.printf("Factorial  8! = %10d\n", factorial ( 8) );
       System.out.printf("Factorial  9! = %10d\n", factorial ( 9) );
       System.out.printf("Factorial 10! = %10d\n", factorial (10) );

       // Demonstrate use of factorials in general arithmetic expressions...

       System.out.printf("\n");
       System.out.printf("Demonstrate factorials in arithmetic expressions\n");
       System.out.printf("================================================\n");

       System.out.printf("Four fours:  7 = %10d\n", factorial(4)/(4+4) + 4 );
       System.out.printf("Four fours: 13 = %10d\n",
                          (int) (factorial(4)*Math.sqrt(4) + 4)/4);

       System.out.printf("================================================\n");

    }
}
