Give a short fragment of Java code that uses the progression classes from Section 2.2.3 to find the eighth value of a Fibonacci progression that starts with 2 and 2 as its first two values.
package Data_Structures.Chapter2;
public class Progression {
// instance variable
protected long current;
/** Constructs a progression starting at zero. */
public Progression() {
this(0);
}
/** Constructs a progression with given start value. */
public Progression(long start) {
current = start;
}
/* Returns the next value of the progression. */
public long nextValue() {
long answer = current;
advance(); // this protected call is responsible for advancing the current value
return answer;
}
/* Advances the current value to the next value of the progression. */
protected void advance() {
current++;
}
/** Prints the next n values of the progression, separated by spaces. */
public void printProgression(int n) {
System.out.print(nextValue()); // print first value without leading space
for (int j = 1; j < n; j++)
System.out.print(" " + nextValue()); // print leading space before others
System.out.println(); // end the line
}
// Here the problem is to find the nth fibonacci value
// we created new method to store the fibonacci values in an array.
// this program returns final value in the given n series.
public long printFinalValueInSeries(int n) {
long[] nthValue = new long[n];
for (int i = 0; i < n; i++) {
nthValue[i] = nextValue();
}
return nthValue[n - 1];
}
}
package Data_Structures.Chapter2;
public class FibonacciProgression extends Progression {
protected long prev;
public FibonacciProgression() {
this(0, 1);
}
/** Constructs generalized Fibonacci, with give first and second values. */
public FibonacciProgression(long first, long second) {
super(first);
prev = second - first; // fictitious value preceding the first
}
/* Replaces (prev,current) with (current, current+prev). */
protected void advance() {
long temp = prev;
prev = current;
current += temp;
}
// We slightly change the driver method to print last value in the progression
public static void main(String args[]) {
Progression prog;
int fibValue = 8;
prog = new FibonacciProgression(2, 2);
System.out.print(fibValue + "th value in the Fibonacci progression with 2, 2 as start values is: ");
System.out.println(prog.printFinalValueInSeries(fibValue));
}
}
Output:
8th value in the Fibonacci progression with 2, 2 as start values: 42