import java.math.BigInteger; import java.util.Scanner; /** * Replace this JavaDoc comment for the purpose of this class */ public class Solution { /** * Gets data from standard input */ private Scanner input = null; /** * Start the execution of the solution * @param args Command line arguments */ public static void main(String args[]) { Solution solution = new Solution(); solution.run(); } // /** * Run the solution. This method is called from main() */ public void run() { // Create object to read data from standard input this.input = new Scanner(System.in); // This code replicates the input to the standard output // Modify this code to solve the problem while ( this.input.hasNextLong() ) { long number = this.input.nextLong(); testIterativeFactorial(number); testTailRecursiveFactorial(number); testRecursiveFactorial(number); } // Close the standard input this.input.close(); } public void testIterativeFactorial(long number) { long start = System.currentTimeMillis(); BigInteger factorial = iterativeFactorial( number ); double duration = (System.currentTimeMillis() - start) / 1000.0; System.out.printf( "Iterative factorial:%n%,d: %.3fs%n%n", factorial, duration ); } public void testTailRecursiveFactorial(long number) { long start = System.currentTimeMillis(); BigInteger factorial = tailRecursiveFactorial( number ); double duration = (System.currentTimeMillis() - start) / 1000.0; System.out.printf( "%n%nTail Recursive factorial:%n%,d: %.3fs%n%n", factorial, duration ); } public void testRecursiveFactorial(long number) { long start = System.currentTimeMillis(); BigInteger factorial = recursiveFactorial( number ); double duration = (System.currentTimeMillis() - start) / 1000.0; System.out.printf( "%n%nRecursive factorial:%n%,d: %.3fs%n%n", factorial, duration ); } public static BigInteger iterativeFactorial(long number) { BigInteger result = BigInteger.valueOf(1); for ( long current = 1; current <= number; ++current ) result = result.multiply( BigInteger.valueOf(current) ); return result; } public static BigInteger recursiveFactorial(long number) { if ( number <= 0 ) return BigInteger.valueOf(1); else return BigInteger.valueOf(number).multiply( recursiveFactorial(number - 1) ); } public static BigInteger tailRecursiveFactorial(long number) { return tailRecursiveFactorial(number, BigInteger.valueOf(1)); } public static BigInteger tailRecursiveFactorial(long number, BigInteger accumulator) { if ( number <= 0 ) return accumulator; else return tailRecursiveFactorial( number - 1, accumulator.multiply( BigInteger.valueOf(number) ) ); } // }