When I testing the code by It keeping saying java.lang.StackOverflowError. I thi
ID: 3713868 • Letter: W
Question
When I testing the code by
It keeping saying java.lang.StackOverflowError. I think It because of this line 'output += calculate(n - i, x);' Can anyone help me fix it, thanks!
public class RecursiveFibonacci f ok * Fibonacci function with a twist. * Consider the normal fibonacci function : F(n) = F(n-1) + F(n-2). * That function can be represented here as F(n)-calculate(n, 2). k The concept here is that calculate(n, x) = calculate(n-1, x) + calculate(n-2, x) + calculate(n-3, x) + +calculate(n -x, x) k @param n The number to calculate the special fibonacci of. * @param x sk The number of recursive terms added to create the next term. arequire x 1 public static int calculate(int n, int x) return 1; else f int output = 0; for (int i-l; ?cx; ++1) { output += calculate( n: n-i, x); return output;Explanation / Answer
Here is the modified code.
public class RecursiveFibonacci
{
/*
* Fibonacci function with a twist.
* Consider the normal fibonacci function: F(n) = F(n-1) + F(n-2).
* That function can be represented here as F(n) = calculate(n, 2).
* The concept here is that
* calculate(n, x) = calculate(n-1, x) + calculate(n-2, x) + calculate(n-3, x) + ...
* + calculate(n-x, x);
*
* @param n
* The number to calculate the special fibonacci of.
* @param x
* The number of recursive terms added to create the next term.
* @require
* n >= 1
* x >= 1
*/
/*
The code for the regular one should be:
if(n==1)
return 1;
else
return F(n-1) + F(n-2)
And the fibonacci series is:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ...
*/
public static int calculate(int n, int x)
{
if(n == 1)
return 1;
else if(n == 2) //This is the key here. And is because, when n == 2, 2-2 will be 0,
//and you didn't defined a value for calculate(0, 2)
return 1;
else
{
int output = 0;
for(int i = 1; i <= x; i++)
output += calculate(n-i, x);
return output;
}
}
}
?And the code is explained in the comments.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.