Skip to content

Commit 186509d

Browse files
authored
Merge pull request #38 from khairalanam/khair
Added Fibonacci Problem Variant
2 parents a97fc40 + e6cde9d commit 186509d

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
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;
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
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");

0 commit comments

Comments
 (0)