A Class that helps with computing Fibonacci numbers, by treating them as linkedlist entries.
Calling FibonacciSequence next() outputs a biginteger for the current fibonacci value of the sequence's instance.
The sequence starts at 1.
import java.math.BigInteger;
public class FibonacciSequence {
private BigInteger first;
private BigInteger second;
public FibonacciSequence() {
second = BigInteger.ONE;
first = BigInteger.ZERO;
}
public BigInteger next() {
BigInteger returnVal = second;
updateValues();
return returnVal;
}
private void updateValues() {
BigInteger t = second;
second = first.add(t);
first = t;
}
}
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
import java.math.BigInteger;
// TODO: Replace examples and use TDD development by writing your own tests
public class SolutionTest {
@Test
public void testSomething() {
assertEquals("1", getFibonacci(1).toString());
assertEquals("1", getFibonacci(2).toString());
assertEquals("2", getFibonacci(3).toString());
assertEquals("3", getFibonacci(4).toString());
assertEquals("5", getFibonacci(5).toString());
assertEquals("8", getFibonacci(6).toString());
assertEquals("13", getFibonacci(7).toString());
assertEquals("21", getFibonacci(8).toString());
assertEquals("34", getFibonacci(9).toString());
assertEquals("55", getFibonacci(10).toString());
assertEquals("89", getFibonacci(11).toString());
assertEquals("144", getFibonacci(12).toString());
assertEquals("233", getFibonacci(13).toString());
}
private BigInteger getFibonacci(long iterations){
FibonacciSequence seq = new FibonacciSequence();
BigInteger result = BigInteger.ZERO;
for(long i = 0; i < iterations; i++){
result = seq.next();
}
return result;
}
}