From 268796b0e8df235a53511dc593d3af47c2e1f1f1 Mon Sep 17 00:00:00 2001 From: Madhurendra Nath Tiwari <68775519+dev-madhurendra@users.noreply.github.com> Date: Tue, 19 Sep 2023 20:29:34 +0530 Subject: [PATCH] added fibonacci using formula along with test cases (#1358) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * added fibonacci using formula along with test cases * updated the changes * added jest's each in test cases * added jest's each for testing * returned inline value * removed redundant comment * hoisted the variables * Use shorthand * considered adding resource of the formula --------- Co-authored-by: madhuredra Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com> --- Maths/Fibonacci.js | 11 +++++++++++ Maths/test/Fibonacci.test.js | 10 +++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/Maths/Fibonacci.js b/Maths/Fibonacci.js index fc8102ad2..998c75302 100644 --- a/Maths/Fibonacci.js +++ b/Maths/Fibonacci.js @@ -187,9 +187,20 @@ const FibonacciMatrixExpo = (num) => { return F[0][0] * (isNeg ? (-ONE) ** (num + ONE) : ONE) } +/* + Resource : https://math.hmc.edu/funfacts/fibonacci-number-formula/ +*/ + +const sqrt5 = Math.sqrt(5) +const phi = (1 + sqrt5) / 2 +const psi = (1 - sqrt5) / 2 + +const FibonacciUsingFormula = n => Math.round((phi ** n - psi ** n) / sqrt5) + export { FibonacciDpWithoutRecursion } export { FibonacciIterative } export { FibonacciGenerator } export { FibonacciRecursive } export { FibonacciRecursiveDP } export { FibonacciMatrixExpo } +export { FibonacciUsingFormula } diff --git a/Maths/test/Fibonacci.test.js b/Maths/test/Fibonacci.test.js index f3dcb98fe..f91aef73d 100644 --- a/Maths/test/Fibonacci.test.js +++ b/Maths/test/Fibonacci.test.js @@ -4,7 +4,8 @@ import { FibonacciIterative, FibonacciGenerator, FibonacciRecursive, - FibonacciMatrixExpo + FibonacciMatrixExpo, + FibonacciUsingFormula } from '../Fibonacci' describe('Fibonacci', () => { @@ -95,4 +96,11 @@ describe('Fibonacci', () => { expect(FibonacciMatrixExpo(-5n)).toBe(5n) expect(FibonacciMatrixExpo(-6n)).toBe(-8n) }) + it.each([ + [0, 0], + [1, 1], + [15, 610] + ])('should calculate the correct Fibonacci number for n = %i', (n, expected) => { + expect(FibonacciUsingFormula(n)).toBe(expected) + }) })