Java Reference
In-Depth Information
quite simple; we'll see several variations of it in the following sections. As a exer-
cise, you might think about how you could rewrite this example using a while
loop instead of a for loop.
Example 1−7: Factorial.java
package com.davidflanagan.examples.basics;
/**
* This class doesn't define a main() method, so it isn't a program by itself.
* It does define a useful method that we can use in other programs, though.
**/
public class Factorial {
/** Compute and return x!, the factorial of x */
public static int factorial(int x) {
if (x < 0) throw new IllegalArgumentException("x must be >= 0");
int fact = 1;
for(int i = 2; i <= x; i++)
// loop
fact *= i;
// shorthand for: fact = fact * i;
return fact;
}
}
Recursive Factorials
Example 1-8 shows another way to compute factorials. This example uses a pro-
gramming technique called recursion . Recursion happens when a method calls
itself, or in other words, invokes itself recursively. The recursive algorithm for
computing factorials relies on the fact that n! is equal to n*(n-1)! . Computing fac-
torials in this fashion is a classic example of recursion. It is not a particularly effi-
cient technique in this case, but there are many important uses for recursion, and
this example demonstrates that it is perfectly legal in Java. This example also
switches from the int data type, which is a 32-bit integer, to the long data type,
which is a 64-bit integer. Factorials become very large, very quickly, so the extra
capacity of a long makes the factorial() method more useful.
Example 1−8: Factorial2.java
package com.davidflanagan.examples.basics;
/**
* This class shows a recursive method to compute factorials. This method
* calls itself repeatedly based on the formula: n! = n * (n-1)!
**/
public class Factorial2 {
public static long factorial(long x) {
if (x < 0) throw new IllegalArgumentException("x must be >= 0");
if (x <= 1) return 1;
// Stop recursing here
else return x * factorial(x-1);
// Recurse by calling ourselves
}
}
Search WWH ::




Custom Search