What does the output statement in main() print out? What is wrong with the implementation of factorial() in this class?
```
public class BadFactorial {
private int n;
public static long factorial () {
if ( n == 1 ) // base case; recursion ends
return 1; // return a result
else {
// recursive case: update input size to
// get closer to base case and iterate again
n = n – 1;
return n * factorial();
}
}
public static main() {
n = 4;
System.out.println("factorial 4 is " + factorial() );
}
}
```
It will print out: “factorial 4 is 6” instead of the actual factorial of 4, which is 24. This is because n is decremented before it is multiplied with the recursive call. The method factorial() will basically be returning the result of this expression: 3 * 2 * 1 * 1.
Commenting out the line n = n – 1; and changing the line that follows it to
return n-- * factorial(); solves the problem.
You might also like to view...
On Format, On Print, and On Retreat are all report ____________________ events.
Fill in the blank(s) with the appropriate word(s).
Which of the following is TRUE about sharing software?
A) When a desktop computer uses software from a server, the software files remain permanently in RAM of the desktop computer. B) Even if software is installed on a server, portions of it must also be installed on the desktop computers. C) If the server where the software is installed is not functioning, the other desktop computers can still use the software. D) Software only has to be installed and updated on one computer.
Which term refers to the loss of signal strength as the signal moves across media?
A. Distortion B. Jitter C. Attenuation D. Impulse noise
Which of the following is a non-linear data structure?
a) linked list b) queue c) binary tree d) stack