diff --git a/Maths/Fibonacci.ts b/Maths/Fibonacci.ts new file mode 100644 index 00000000..b924c91a --- /dev/null +++ b/Maths/Fibonacci.ts @@ -0,0 +1,25 @@ +/** + * A function to get nth Fibonacci number + * @param number The input integer + * @return {number} Fibonacci number of `number` + * @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; + + let a = 0, b = 1; + + for (let i = 1; i < number; ++i) { + const c = a + b; + + a = b; + b = c; + } + + return b; +}; diff --git a/Maths/test/Fibonacci.test.ts b/Maths/test/Fibonacci.test.ts new file mode 100644 index 00000000..0a379ed7 --- /dev/null +++ b/Maths/test/Fibonacci.test.ts @@ -0,0 +1,11 @@ +import {nthFibonacci} 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