Calculate the factorial (and display calls and return values)
@author
@version
import java.util.Scanner;
public class Factorial{
public static void main( String[] args ){
Scanner stdinScanner = new Scanner( System.in );
int nInitial;
long result;
System.out.print( "Please enter a whole number: ");
nInitial = stdinScanner.nextInt();
result = factorial( nInitial );
System.out.println( "factorial(" + nInitial + ") = " + result + " (in main())");
}
Iterative method to calculate the factorial of n
(n!) = n * (n-1) * (n-2) ...
@param n
@return
public static long factorialIterative( int n ){
long product = n;
for( int i = n - 1; i >= 1; --i){
product *= i;
}
return product;
}
Recursive method to calculate the factorial of n
(n!) = n * (n-1)!
@param n
@return
public static long factorial( int n ){
long product = 1;
System.out.println( "factorial( " + n + ")");
if( n == 0 ){
product = 1;
}else{
product = n * factorial( n - 1 );
}
System.out.println( "returning " + product );
return product;
}
}