Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: Can't figure out this recursive problem
|
Posted: Dec 13, 2002 3:01 PM
|
|
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) + "." );
}
}
|
|