Skip to content

Commit

Permalink
add: get Nth Fibonacci algorithm implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
EliasAfara committed Oct 16, 2023
1 parent 6e6a0ac commit cba0219
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
27 changes: 27 additions & 0 deletions Recursion/NthFibonacci.js
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 };
21 changes: 21 additions & 0 deletions Recursion/tests/NthFibonacci.test.js
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);
});
});

0 comments on commit cba0219

Please sign in to comment.