Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Math processing
Expertise: Beginner
Mar 21, 1997

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!
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date