File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed
src/com/codefortomorrow/advanced/chapter13/examples Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .codefortomorrow .advanced .chapter13 .examples ;
2
+
3
+ public class Fibonacci {
4
+ public static int fibonacciRecursion (int nthNumber ) {
5
+ //use recursion
6
+ if (nthNumber == 0 ) {
7
+ return 0 ;
8
+ } else if (nthNumber == 1 ) {
9
+ return 1 ;
10
+ }
11
+ return fibonacciRecursion (nthNumber - 1 ) + fibonacciRecursion (nthNumber - 2 );
12
+ }
13
+
14
+ public static int fibonacciLoop (int nthNumber ) {
15
+ //use loop
16
+ int previouspreviousNumber , previousNumber = 0 , currentNumber = 1 ;
17
+ for (int i = 1 ; i < nthNumber ; i ++) {
18
+ previouspreviousNumber = previousNumber ;
19
+ previousNumber = currentNumber ;
20
+ currentNumber = previouspreviousNumber + previousNumber ;
21
+ }
22
+ return currentNumber ;
23
+ }
24
+
25
+ // Credit: https://dev.to/khalilsaboor/fibonacci-recursion-vs-iteration--474l
26
+ }
You can’t perform that action at this time.
0 commit comments