diff --git a/maths/fibonacci.ts b/maths/fibonacci.ts index b924c91a..33013d68 100644 --- a/maths/fibonacci.ts +++ b/maths/fibonacci.ts @@ -1,19 +1,26 @@ /** - * A function to get nth Fibonacci number - * @param number The input integer - * @return {number} Fibonacci number of `number` + * A function to get nth Fibonacci number. + * + * Time Complexity: linear (O(n)) + * + * @param number The index of the number in the Fibonacci sequence. + * @return The Fibonacci number on the nth index in the sequence. + * * @example nthFibonacci(4) => 3 | nthFibonacci(6) => 8 * @see https://en.m.wikipedia.org/wiki/Fibonacci_number * @author MohdFaisalBidda */ - export const nthFibonacci = (number: number): number => { - if (number < 0) throw "Number should be greater than 0"; - - if (number === 0) return 0; + if (number < 0) { + throw 'Number should be greater than 0'; + } - let a = 0, b = 1; + if (number === 0) { + return 0; + } + let a = 0, + b = 1; for (let i = 1; i < number; ++i) { const c = a + b; @@ -23,3 +30,29 @@ export const nthFibonacci = (number: number): number => { return b; }; + +/** + * A function to get nth Fibonacci number recursively. **Note: This recursive approach increases the time complexity** + * + * Time Complexity: exponential (O(ϕ^n)) + * + * @param number The index of the number in the Fibonacci sequence. + * @return The Fibonacci number on the nth index in the sequence. + * + * @example nthFibonacci(4) => 3 | nthFibonacci(6) => 8 + * @see https://en.m.wikipedia.org/wiki/Fibonacci_number + * @author zFlxw + */ +export const nthFibonacciRecursively = (number: number): number => { + if (number === 0) { + return 0; + } + + if (number <= 2) { + return 1; + } + + return ( + nthFibonacciRecursively(number - 1) + nthFibonacciRecursively(number - 2) + ); +}; diff --git a/maths/test/fibonacci.test.ts b/maths/test/fibonacci.test.ts index 578d7b79..e0a8d14b 100644 --- a/maths/test/fibonacci.test.ts +++ b/maths/test/fibonacci.test.ts @@ -1,11 +1,13 @@ -import {nthFibonacci} from '../fibonacci'; +import { nthFibonacci, nthFibonacciRecursively } from '../fibonacci'; -describe('nthFibonacci', () => { - test('should return correct value', () => { - expect(nthFibonacci(0)).toBe(0); - expect(nthFibonacci(1)).toBe(1); - expect(nthFibonacci(5)).toBe(5); - expect(nthFibonacci(4)).toBe(3); - expect(nthFibonacci(0)).toBe(0); - }); -}); \ No newline at end of file +const test = (func: (n: number) => number) => + it.each([ + [0, 0], + [1, 1], + [2, 1], + [5, 5], + [10, 55], + [15, 610], + ])('fib(%i) = %i', (n, expected) => expect(func(n)).toBe(expected)); +describe('Fibonacci iterative', () => test(nthFibonacci)); +describe('Fibonacci recursive', () => test(nthFibonacciRecursively));