"Algorithms in C by Sedgewick "
yes! excellent book it's got a high place on my shelf.
um just looking at there's infinite recursion. where's the base case? you're calling output(n - 2) for ever and ever.
in general recursion is very inefficent. function call overhead aside, it's slower than an iterative approach. using a stack like suggested is a good idea.
rewriting this without a base case is impossible / a total waste of time, so i won't attempt. you can easily rewrite it iteratively though, just give it some thought. but real quick, you can eliminate the input function by using the ternary operator. and since the second operand of that expression is known to be 0 or 1, just say 0 or 0.5.
Code:
public int output(int n) {
return (n - 1 < 0 ? 0 : 0.5) + 1.9 * output(n - 1) + 0.9 * output(n - 2);
}
Bookmarks