Facundo Ezequiel Candido - 2 months ago 9

Java Question

I need to write java methods to compute the Fibonacci series of ANY first two numbers imputed by the user, let's say that the user inputs 10 and 20, and wants the first 5 numbers of the series, the output would be 10 20 30 50 80. I have already implemented an iterative method that does this, but my trouble is with the RECURSIVE method to accomplish it.

`public int fRec(int n)`

{

//base case of recursion

if ((n == 0) || (n == 1))

return n;

else

//recursive step

return fRec(n-1) + fRec(n-2);

}

this is the typical recursive method to the fibonacci series, the n parameter represents up to what number the user wants the series to run, but how can i modify it to to make sure that the series uses the first two numbers that the user wants the series to begin with?

Answer

To start with specific numbers in the series they will need to be returned for 0 and 1:

```
public int fib(int n, int start1, int start2) {
switch (n) {
case 0: return start1;
case 1: return start2;
default: return fib(n-1, start1, start2) + fib(n-2, start1, start2);
}
}
```

This is a pretty laborious way to calculate several members of the series as it's going all the way back to the start each time. Better would be to encapsulate in a class:

```
class Fib {
private int previous;
private int current;
public Fib(int start1, int start2) {
this.previous = start1;
this.current = start2;
}
public int next() {
int temp = previous + current;
previous = current;
current = successor;
return current;
}
}
```

Source (Stackoverflow)

Comments