File tree Expand file tree Collapse file tree
main/java/com/baeldung/fibonacci
test/java/com/baeldung/fibonacci Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments