BAEL-3519 (#8169)
* BAEL-3519 - Fibonacci Series - Recursive method - Iterative method * - Added new method that uses Golden Ratio to calculate the given term of Fibonacci Series * added binet formula implementation of constant time for fibonacci term
This commit is contained in:
parent
592d3e27d7
commit
ac8d8b824f
@ -0,0 +1,34 @@
|
|||||||
|
package com.baeldung.fibonacci;
|
||||||
|
|
||||||
|
import static java.lang.Math.pow;
|
||||||
|
|
||||||
|
public class FibonacciSeriesUtils {
|
||||||
|
|
||||||
|
public static int nthFibonacciTermRecursiveMethod(int n) {
|
||||||
|
if (n == 0 || n == 1) {
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
return nthFibonacciTermRecursiveMethod(n - 1) + nthFibonacciTermRecursiveMethod(n - 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int nthFibonacciTermIterativeMethod(int n) {
|
||||||
|
if (n == 0 || n == 1) {
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
int n0 = 0, n1 = 1;
|
||||||
|
int tempNthTerm;
|
||||||
|
for (int i = 2; i <= n; i++) {
|
||||||
|
tempNthTerm = n0 + n1;
|
||||||
|
n0 = n1;
|
||||||
|
n1 = tempNthTerm;
|
||||||
|
}
|
||||||
|
return n1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int nthFibonacciTermUsingBinetsFormula(int n) {
|
||||||
|
final double squareRootOf5 = Math.sqrt(5);
|
||||||
|
final double phi = (1 + squareRootOf5)/2;
|
||||||
|
int nthTerm = (int) ((Math.pow(phi, n) - Math.pow(-phi, -n))/squareRootOf5);
|
||||||
|
return nthTerm;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,29 @@
|
|||||||
|
package com.baeldung.fibonacci;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class FibonacciSeriesUtilsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTermToCalculate_thenReturnThatTermUsingRecursion() {
|
||||||
|
int term = 10;
|
||||||
|
int expectedValue = 55;
|
||||||
|
assertEquals(FibonacciSeriesUtils.nthFibonacciTermRecursiveMethod(term), expectedValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTermToCalculate_thenReturnThatTermUsingIteration() {
|
||||||
|
int term = 10;
|
||||||
|
int expectedValue = 55;
|
||||||
|
assertEquals(FibonacciSeriesUtils.nthFibonacciTermIterativeMethod(term), expectedValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTermToCalculate_thenReturnThatTermUsingBinetsFormula() {
|
||||||
|
int term = 10;
|
||||||
|
int expectedValue = 55;
|
||||||
|
assertEquals(FibonacciSeriesUtils.nthFibonacciTermUsingBinetsFormula(term), expectedValue);
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user