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