File tree Expand file tree Collapse file tree 3 files changed +70
-0
lines changed
L-B/0020 NthFibonacciNumberO(1) Expand file tree Collapse file tree 3 files changed +70
-0
lines changed Original file line number Diff line number Diff line change 1+ const NthFibonacciNumber = ( n ) => {
2+ root_five = Math . sqrt ( 5 ) ;
3+ major_term = ( 1 + root_five ) / 2 ;
4+ minor_term = ( 1 - root_five ) / 2 ;
5+
6+ return Math . round (
7+ ( 1 / root_five ) * ( Math . pow ( major_term , n ) - Math . pow ( minor_term , n ) )
8+ ) ;
9+ } ;
10+
11+ module . exports = NthFibonacciNumber ;
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
Original file line number Diff line number Diff line change 1+ const { strict : assert } = require ( "assert" ) ;
2+ const NthFibonacciNumber = require ( "./NthFibonacciNumberO(1)" ) ;
3+
4+ assert . equal ( NthFibonacciNumber ( 0 ) , 0 ) ;
5+ assert . equal ( NthFibonacciNumber ( 1 ) , 1 ) ;
6+ assert . equal ( NthFibonacciNumber ( 2 ) , 1 ) ;
7+ assert . equal ( NthFibonacciNumber ( 3 ) , 2 ) ;
8+ assert . equal ( NthFibonacciNumber ( 6 ) , 8 ) ;
9+ assert . equal ( NthFibonacciNumber ( 10 ) , 55 ) ;
10+ assert . equal ( NthFibonacciNumber ( 30 ) , 832040 ) ;
11+ assert . equal ( NthFibonacciNumber ( 50 ) , 12586269025 ) ;
12+
13+ console . log ( "All testcases completed successfully" ) ;
You can’t perform that action at this time.
0 commit comments