Skip to content

Commit b8f6f9d

Browse files
vatsalgosarsjmillington
authored andcommitted
BAEL-3519 (eugenp#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
1 parent 0259c56 commit b8f6f9d

2 files changed

Lines changed: 63 additions & 0 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.baeldung.fibonacci;
2+
3+
import static java.lang.Math.pow;
4+
5+
public class FibonacciSeriesUtils {
6+
7+
public static int nthFibonacciTermRecursiveMethod(int n) {
8+
if (n == 0 || n == 1) {
9+
return n;
10+
}
11+
return nthFibonacciTermRecursiveMethod(n - 1) + nthFibonacciTermRecursiveMethod(n - 2);
12+
}
13+
14+
public static int nthFibonacciTermIterativeMethod(int n) {
15+
if (n == 0 || n == 1) {
16+
return n;
17+
}
18+
int n0 = 0, n1 = 1;
19+
int tempNthTerm;
20+
for (int i = 2; i <= n; i++) {
21+
tempNthTerm = n0 + n1;
22+
n0 = n1;
23+
n1 = tempNthTerm;
24+
}
25+
return n1;
26+
}
27+
28+
public static int nthFibonacciTermUsingBinetsFormula(int n) {
29+
final double squareRootOf5 = Math.sqrt(5);
30+
final double phi = (1 + squareRootOf5)/2;
31+
int nthTerm = (int) ((Math.pow(phi, n) - Math.pow(-phi, -n))/squareRootOf5);
32+
return nthTerm;
33+
}
34+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.baeldung.fibonacci;
2+
3+
import static org.junit.Assert.assertEquals;
4+
5+
import org.junit.Test;
6+
7+
public class FibonacciSeriesUtilsUnitTest {
8+
9+
@Test
10+
public void givenTermToCalculate_thenReturnThatTermUsingRecursion() {
11+
int term = 10;
12+
int expectedValue = 55;
13+
assertEquals(FibonacciSeriesUtils.nthFibonacciTermRecursiveMethod(term), expectedValue);
14+
}
15+
16+
@Test
17+
public void givenTermToCalculate_thenReturnThatTermUsingIteration() {
18+
int term = 10;
19+
int expectedValue = 55;
20+
assertEquals(FibonacciSeriesUtils.nthFibonacciTermIterativeMethod(term), expectedValue);
21+
}
22+
23+
@Test
24+
public void givenTermToCalculate_thenReturnThatTermUsingBinetsFormula() {
25+
int term = 10;
26+
int expectedValue = 55;
27+
assertEquals(FibonacciSeriesUtils.nthFibonacciTermUsingBinetsFormula(term), expectedValue);
28+
}
29+
}

0 commit comments

Comments
 (0)