The Artima Developer Community
Sponsored Link

Java Answers Forum
Can't figure out this recursive problem

1 reply. Most recent reply: Dec 13, 2002 3:01 PM by Matt Gerrans

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a flat view of this topic  Flat View
Previous Topic   Next Topic
Threaded View: This topic has 1 reply on 1 page
Brady Hales

Posts: 1
Nickname: brady
Registered: Dec, 2002

Can't figure out this recursive problem Posted: Dec 13, 2002 10:56 AM
Reply to this message Reply
I'm trying to write a program that will calculate inverse factorial numbers (i.e. 1/n!). I want to use a recursive method, but I have problems with it dividing by zero. What can I do to prevent this?

Here is my code:


public class InFact
{
private static double InFact(double n)
{

return (InFact(1/n) * InFact(1/(n-1)));

}


public static void main (String args[])
{
final double NUM = 5;
double result;

result = InFact(NUM);

System.out.println("The result is: " + result);


}

}


Re: Can't figure out this recursive problem Posted: Dec 13, 2002 3:01 PM
Reply to this message Reply
Posted by: Matt Gerrans    Posts: 1153 / Nickname: matt / Registered: Feb, 2002
Hows this? Note that you can save the division 'til the end, which avoids a lot of wasted processing.

public class InFact
{
   private static long getFactorial( long n )
   {
      return n > 1 ? n * getFactorial( n - 1 ) : 1;
   }
 
   private static double getInverseFactorial( long n )
   {
      return 1.0 / getFactorial(n);
   }
 
   public static void main (String args[])
   {
      long NUM = 5;
      try
      {
         if( args.length == 1 )
            NUM = Integer.parseInt(args[0]);
      }
      catch( java.lang.NumberFormatException nfe )
      {
         System.out.println( "Try specifying an integer value next time." );
      }
 
      System.out.println( "The factorial of " + NUM + 
                          " is " + getFactorial(NUM) +
                          ", the \"inverse factorial\" is " +
                          getInverseFactorial(NUM) + "." );
   }
}


Topic: loops Previous Topic   Next Topic Topic: JSP PAGING

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use