Writing a Factorial Method

Question:
Can you help me complete the enclosed program? A “Factorial Method”must be written.

/////// 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 +")");    } } 
We can compile and run this program as follows:
% 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:

private int factorial (int n) {      int result = 1;      for(int i = 2; i <= n; i++)         result *= i;      return result;   } 
Now you write the recursive version!

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: