Recursive factorial method for BigInteger. - Java Object Oriented Design

Java examples for Object Oriented Design:Method Recursive

Description

Recursive factorial method for BigInteger.

Demo Code

import java.math.BigInteger;

public class Main
{
   // recursive method factorial (assumes its parameter is >= 0)
   public static BigInteger factorial(BigInteger number)
   {/* w ww .  j a v  a 2s  .c  o m*/
      if (number.compareTo(BigInteger.ONE) <= 0) // test base case
         return BigInteger.ONE; 
      else // recursion step
         return number.multiply(factorial(number.subtract(BigInteger.ONE)));
   } 

   // output factorials for values 0-50
   public static void main(String[] args)
   {
      // calculate the factorials of 0 through 50
      for (int counter = 0; counter <= 50; counter++){
         System.out.printf("%d! = %d%n", counter, 
            factorial(BigInteger.valueOf(counter)));
      }
   } 
}

Result


Related Tutorials