Skip to content

Commit 092d16a

Browse files
feat: add iterative Fibonacci algorithm
1 parent 5c39e87 commit 092d16a

2 files changed

Lines changed: 66 additions & 0 deletions

File tree

‎Maths/FibonacciIterative.js‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @function fibonacciIterative
3+
* @description Returns the nth Fibonacci number using an iterative approach.
4+
* The Fibonacci sequence starts with 0 and 1, and each subsequent number
5+
* is the sum of the two preceding ones: 0, 1, 1, 2, 3, 5, 8, 13, ...
6+
* @param {number} n - The position in the Fibonacci sequence (0-indexed)
7+
* @returns {number} - The nth Fibonacci number
8+
* @see https://en.wikipedia.org/wiki/Fibonacci_sequence
9+
* @example fibonacciIterative(0) => 0
10+
* @example fibonacciIterative(6) => 8
11+
* @example fibonacciIterative(10) => 55
12+
*/
13+
const fibonacciIterative = (n) => {
14+
if (!Number.isInteger(n) || n < 0) {
15+
throw new TypeError('Input must be a non-negative integer')
16+
}
17+
if (n === 0) return 0
18+
if (n === 1) return 1
19+
let a = 0
20+
let b = 1
21+
for (let i = 2; i <= n; i++) {
22+
;[a, b] = [b, a + b]
23+
}
24+
return b
25+
}
26+
27+
export { fibonacciIterative }
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { fibonacciIterative } from '../FibonacciIterative.js'
2+
3+
describe('fibonacciIterative', () => {
4+
test('fibonacciIterative(0) returns 0', () => {
5+
expect(fibonacciIterative(0)).toBe(0)
6+
})
7+
8+
test('fibonacciIterative(1) returns 1', () => {
9+
expect(fibonacciIterative(1)).toBe(1)
10+
})
11+
12+
test('fibonacciIterative(2) returns 1', () => {
13+
expect(fibonacciIterative(2)).toBe(1)
14+
})
15+
16+
test('fibonacciIterative(5) returns 5', () => {
17+
expect(fibonacciIterative(5)).toBe(5)
18+
})
19+
20+
test('fibonacciIterative(6) returns 8', () => {
21+
expect(fibonacciIterative(6)).toBe(8)
22+
})
23+
24+
test('fibonacciIterative(10) returns 55', () => {
25+
expect(fibonacciIterative(10)).toBe(55)
26+
})
27+
28+
test('fibonacciIterative(20) returns 6765', () => {
29+
expect(fibonacciIterative(20)).toBe(6765)
30+
})
31+
32+
test('throws TypeError for negative input', () => {
33+
expect(() => fibonacciIterative(-1)).toThrow(TypeError)
34+
})
35+
36+
test('throws TypeError for float input', () => {
37+
expect(() => fibonacciIterative(1.5)).toThrow(TypeError)
38+
})
39+
})

0 commit comments

Comments
 (0)