go to previous page   go to home page   go to next page highlighting

Answer:

Overflow


Overflow

Factorial gets very big quickly, and values overflow the capacity of 64-bit longs.

Also recall that Java gives you no indication that this happened. (Some programming languages will flag the problem.)

It is almost always a mistake to explicitly calculate factorial. Usually when you implement a math function that uses factorial there is a way to remove factorial from the formula. The resulting formula may not be mathematically elegant, but works better for programming.

(For more on this topic, see the chapter on BigInteger.)


QUESTION 9:

(Review: ) Is there anything wrong with factorial( int N )the following program? Its parameter N has the same name as the variable in main() .

public class UnitTest
{
  
  public static long factorial( int N )
  {
    long fct = 1;
    for ( int j=1; j<=N; j++ )
      fct *= j;
    return fct;
  }
  
  public static void main (String[] args ) 
  {
     int N = 10;
     System.out.println( "factorial of " + N + ": " + factorial( N ) );
  }
}

go to previous page   go to home page   go to next page