1
1
/**
2
- * A function to get nth Fibonacci number
3
- * @param number The input integer
4
- * @return {number } Fibonacci number of `number`
2
+ * A function to get nth Fibonacci number.
3
+ *
4
+ * Time Complexity: linear (O(n))
5
+ *
6
+ * @param number The index of the number in the Fibonacci sequence.
7
+ * @return The Fibonacci number on the nth index in the sequence.
8
+ *
5
9
* @example nthFibonacci(4) => 3 | nthFibonacci(6) => 8
6
10
* @see https://en.m.wikipedia.org/wiki/Fibonacci_number
7
11
* @author MohdFaisalBidda <https://github.com/MohdFaisalBidda>
8
12
*/
9
-
10
13
export const nthFibonacci = ( number : number ) : number => {
11
- if ( number < 0 ) throw "Number should be greater than 0" ;
12
-
13
- if ( number === 0 ) return 0 ;
14
+ if ( number < 0 ) {
15
+ throw 'Number should be greater than 0' ;
16
+ }
14
17
15
- let a = 0 , b = 1 ;
18
+ if ( number === 0 ) {
19
+ return 0 ;
20
+ }
16
21
22
+ let a = 0 ,
23
+ b = 1 ;
17
24
for ( let i = 1 ; i < number ; ++ i ) {
18
25
const c = a + b ;
19
26
@@ -23,3 +30,29 @@ export const nthFibonacci = (number: number): number => {
23
30
24
31
return b ;
25
32
} ;
33
+
34
+ /**
35
+ * A function to get nth Fibonacci number recursively. **Note: This recursive approach increases the time complexity**
36
+ *
37
+ * Time Complexity: exponential (O(ϕ^n))
38
+ *
39
+ * @param number The index of the number in the Fibonacci sequence.
40
+ * @return The Fibonacci number on the nth index in the sequence.
41
+ *
42
+ * @example nthFibonacci(4) => 3 | nthFibonacci(6) => 8
43
+ * @see https://en.m.wikipedia.org/wiki/Fibonacci_number
44
+ * @author zFlxw <https://github.com/zFlxw>
45
+ */
46
+ export const nthFibonacciRecursively = ( number : number ) : number => {
47
+ if ( number === 0 ) {
48
+ return 0 ;
49
+ }
50
+
51
+ if ( number <= 2 ) {
52
+ return 1 ;
53
+ }
54
+
55
+ return (
56
+ nthFibonacciRecursively ( number - 1 ) + nthFibonacciRecursively ( number - 2 )
57
+ ) ;
58
+ } ;
0 commit comments