-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add: get Nth Fibonacci algorithm implementation
- Loading branch information
1 parent
6e6a0ac
commit cba0219
Showing
2 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
/** | ||
* Get the nth Fibonacci number. | ||
* | ||
* @param {number} n - The position of the Fibonacci number to find. | ||
* @returns {number} - The nth Fibonacci number. | ||
* | ||
* @description | ||
* The Fibonacci sequence is defined as follows: the first number of the sequence is 0, the second number is 1, | ||
* and the nth number is the sum of the (n - 1)th and (n - 2)th numbers. | ||
* | ||
* For the purpose of this function, the first Fibonacci number is F0; therefore, getNthFib(1) is equal to F0, | ||
* getNthFib(2) is equal to F1, and so on. | ||
* | ||
* The function uses a recursive approach to calculate the Fibonacci number for a given position. | ||
* | ||
* @Complexity | ||
* The time complexity of this function is O(2^n), which makes it inefficient for large values of n. | ||
* This is because it recalculates Fibonacci numbers multiple times for the same values. | ||
*/ | ||
function getNthFib(n) { | ||
if (n === 0) return 0; | ||
if (n === 1) return 0; | ||
if (n === 2) return 1; | ||
return getNthFib(n - 1) + getNthFib(n - 2); | ||
} | ||
|
||
export { getNthFib }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import { getNthFib } from "../NthFibonacci"; | ||
|
||
describe("getNthFib", () => { | ||
it("should return the correct Fibonacci number for a given position", () => { | ||
expect(getNthFib(0)).toBe(0); | ||
expect(getNthFib(1)).toBe(0); | ||
expect(getNthFib(2)).toBe(1); | ||
expect(getNthFib(3)).toBe(1); | ||
expect(getNthFib(4)).toBe(2); | ||
expect(getNthFib(5)).toBe(3); | ||
expect(getNthFib(6)).toBe(5); | ||
expect(getNthFib(7)).toBe(8); | ||
expect(getNthFib(8)).toBe(13); | ||
expect(getNthFib(9)).toBe(21); | ||
expect(getNthFib(10)).toBe(34); | ||
expect(getNthFib(15)).toBe(377); | ||
expect(getNthFib(20)).toBe(4181); | ||
expect(getNthFib(25)).toBe(46368); | ||
expect(getNthFib(30)).toBe(514229); | ||
}); | ||
}); |