-
-
Notifications
You must be signed in to change notification settings - Fork 408
/
Copy pathfibonacci.ts
80 lines (71 loc) · 2.19 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* 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>
*/
function* generateFibonacci(): Generator<number> {
let a = 0
let b = 1
while (true) {
yield a
const c = a + b
a = b
b = c
}
}
export const nthFibonacci = (number: number): number => {
if (isNaN(number)) throw new Error('The input needs to be a number')
if (!Number.isInteger(number) || number < 0)
throw new Error('The input needs to be a non-negative integer')
if (number === 0) {
return 0
}
const fibonacciGenerator = generateFibonacci()
let result = 0
for (let i = 0; i <= number; ++i) {
result = fibonacciGenerator.next().value
}
return result
}
/**
* 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)
)
}
/**
* @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://math.hmc.edu/funfacts/fibonacci-number-formula/
* @author : dev-madhurendra<https://github.com/dev-madhurendra>
*/
const sqrt5 = Math.sqrt(5)
const phi = (1 + sqrt5) / 2
const psi = (1 - sqrt5) / 2
export const nthFibonacciUsingFormula = (n: number) =>
Math.round((phi ** n - psi ** n) / sqrt5)