diff --git a/Recursion/NthFibonacci.js b/Recursion/NthFibonacci.js new file mode 100644 index 0000000..4752215 --- /dev/null +++ b/Recursion/NthFibonacci.js @@ -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 }; diff --git a/Recursion/tests/NthFibonacci.test.js b/Recursion/tests/NthFibonacci.test.js new file mode 100644 index 0000000..4f8c38a --- /dev/null +++ b/Recursion/tests/NthFibonacci.test.js @@ -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); + }); +});