File tree 1 file changed +46
-0
lines changed
L-B/0020 NthFibonacciNumberO(1)
1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 0020 NthNumberFibonacci ( L-B )
2
+
3
+ ## Problem
4
+
5
+ Create a function that calculates the nth fibonacci number in O(1) time.
6
+
7
+ Fibonacci starts with ` 0 ` and ` 1 `
8
+
9
+ F(n) = (1 / sqrt(5)) \* ((1 + sqrt(5) / 2) ^ n - (1 - sqrt(5) / 2) ^ n)
10
+
11
+ ## Test Cases
12
+
13
+ - NthFibonacciNumber(0) // 0
14
+ - NthFibonacciNumber(1) // 1
15
+ - NthFibonacciNumber(2) // 1
16
+ - NthFibonacciNumber(3) // 2
17
+ - NthFibonacciNumber(6) // 8
18
+ - NthFibonacciNumber(10) // 55
19
+ - NthFibonacciNumber(30) // 832040
20
+ - NthFibonacciNumber(50) // 12586269025
21
+
22
+ ## Solution
23
+
24
+ ``` javascript
25
+ const NthFibonacciNumber = (n ) => {
26
+ root_five = Math .sqrt (5 );
27
+ major_term = (1 + root_five) / 2 ;
28
+ minor_term = (1 - root_five) / 2 ;
29
+
30
+ return Math .round (
31
+ (1 / root_five) * (Math .pow (major_term, n) - Math .pow (minor_term, n))
32
+ );
33
+ };
34
+ ```
35
+
36
+ ## References
37
+
38
+ - [ Math Stack Exchange] ( https://math.stackexchange.com/questions/1105093/proving-a-slight-variation-of-the-fibonacci-formula-using-complete-induction )
39
+
40
+ ## Problem Added By
41
+
42
+ - [ khairalanam] ( https://github.com/khairalanam )
43
+
44
+ ## Contributing
45
+
46
+ If you have the idea to optimise the solution, then please feel free to open a pull request and let me know about your optimization : D
You can’t perform that action at this time.
0 commit comments