From 092d16a657435063f2fb8a470474ab63997192fc Mon Sep 17 00:00:00 2001 From: sarthakgupta1907-cell Date: Mon, 2 Nov 2026 18:20:56 +0530 Subject: [PATCH] feat: add iterative Fibonacci algorithm --- Maths/FibonacciIterative.js | 27 +++++++++++++++++++ Maths/test/FibonacciIterative.test.js | 39 +++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 Maths/FibonacciIterative.js create mode 100644 Maths/test/FibonacciIterative.test.js diff --git a/Maths/FibonacciIterative.js b/Maths/FibonacciIterative.js new file mode 100644 index 0000000000..49308b5774 --- /dev/null +++ b/Maths/FibonacciIterative.js @@ -0,0 +1,27 @@ +/** + * @function fibonacciIterative + * @description Returns the nth Fibonacci number using an iterative approach. + * The Fibonacci sequence starts with 0 and 1, and each subsequent number + * is the sum of the two preceding ones: 0, 1, 1, 2, 3, 5, 8, 13, ... + * @param {number} n - The position in the Fibonacci sequence (0-indexed) + * @returns {number} - The nth Fibonacci number + * @see https://en.wikipedia.org/wiki/Fibonacci_sequence + * @example fibonacciIterative(0) => 0 + * @example fibonacciIterative(6) => 8 + * @example fibonacciIterative(10) => 55 + */ +const fibonacciIterative = (n) => { + if (!Number.isInteger(n) || n < 0) { + throw new TypeError('Input must be a non-negative integer') + } + if (n === 0) return 0 + if (n === 1) return 1 + let a = 0 + let b = 1 + for (let i = 2; i <= n; i++) { + ;[a, b] = [b, a + b] + } + return b +} + +export { fibonacciIterative } diff --git a/Maths/test/FibonacciIterative.test.js b/Maths/test/FibonacciIterative.test.js new file mode 100644 index 0000000000..e5d2710ea1 --- /dev/null +++ b/Maths/test/FibonacciIterative.test.js @@ -0,0 +1,39 @@ +import { fibonacciIterative } from '../FibonacciIterative.js' + +describe('fibonacciIterative', () => { + test('fibonacciIterative(0) returns 0', () => { + expect(fibonacciIterative(0)).toBe(0) + }) + + test('fibonacciIterative(1) returns 1', () => { + expect(fibonacciIterative(1)).toBe(1) + }) + + test('fibonacciIterative(2) returns 1', () => { + expect(fibonacciIterative(2)).toBe(1) + }) + + test('fibonacciIterative(5) returns 5', () => { + expect(fibonacciIterative(5)).toBe(5) + }) + + test('fibonacciIterative(6) returns 8', () => { + expect(fibonacciIterative(6)).toBe(8) + }) + + test('fibonacciIterative(10) returns 55', () => { + expect(fibonacciIterative(10)).toBe(55) + }) + + test('fibonacciIterative(20) returns 6765', () => { + expect(fibonacciIterative(20)).toBe(6765) + }) + + test('throws TypeError for negative input', () => { + expect(() => fibonacciIterative(-1)).toThrow(TypeError) + }) + + test('throws TypeError for float input', () => { + expect(() => fibonacciIterative(1.5)).toThrow(TypeError) + }) +})