Question:
Can you help me complete the enclosed program? A “Factorial Method”must be written.
We can compile and run this program as follows://///// File: Factorial.java /////// class Factorial { /* put factorial method here */ public static void main(String[] args) { if ( args.length != 1 ) System.err.println(“Usage: Factorial n”); // converts string to int int n = Integer.valueOf(args[0]).intValue(); if ( n >= 0 && n < 13 ) System.out.println(factorial(n)); else System.err.println("Factorial("+ n +")"); } }
% javac Factorial.java % java Factorial 6
Answer:
We can compile and run this program as follows:
% javac Factorial.java % java Factorial 6
It looks pretty good. All you need is a factorial function:
Now you write the recursive version!private int factorial (int n) { int result = 1; for(int i = 2; i <= n; i++) result *= i; return result; }