Fig. 18.3 Recursive factorial method.


 1   // Fig. 18.3: FactorialCalculator.java
 2   // Recursive factorial method.
 3
 4   public class FactorialCalculator {
 5   // recursive method factorial (assumes its parameter is >= 0)
 6      public static long factorial(long number)                    
 7         if (number <= 1) // test for base case                    
 8            return 1; // base cases: 0! = 1 and 1! = 1             
 9         }
10         else // recursion step                                    
11            return number * factorial(number - 1);                 
12         }
13      }                                                            
14
15      public static void main(String[] ...

Get Java How To Program, Late Objects, 11th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.