Skip to content

Commit 4434493

Browse files
committed
Added Fibonacci Number with recursion in DP
1 parent 7a1141b commit 4434493

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @function fibonacci
3+
* @description Fibonacci is the sum of previous two fibonacci numbers.
4+
* @param {Integer} N - The input integer
5+
* @return {Integer} fibonacci of N.
6+
* @see [Fibonacci_Numbers](https://en.wikipedia.org/wiki/Fibonacci_number)
7+
*/
8+
const fibonacci = (N) => {
9+
if (!Number.isInteger(N)) {
10+
throw new TypeError('Input should be integer')
11+
}
12+
const dp = new Map()
13+
return fiboDP(N, dp)
14+
}
15+
16+
const fiboDP = (N, dp) => {
17+
if (N <= 1) return N
18+
19+
if (dp.has(N)) return dp.get(N)
20+
21+
const result = fiboDP(N - 1, dp) + fiboDP(N - 2, dp)
22+
dp.set(N, result)
23+
return result
24+
}
25+
26+
export { fibonacci }
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { fibonacci } from '../FibonacciNumberRecursive'
2+
3+
describe('Testing FibonacciNumberRecursive', () => {
4+
it('fibonacci of 0', () => {
5+
expect(fibonacci(0)).toBe(0)
6+
})
7+
8+
it('fibonacci of 1', () => {
9+
expect(fibonacci(1)).toBe(1)
10+
})
11+
12+
it('fibonacci of 10', () => {
13+
expect(fibonacci(10)).toBe(55)
14+
})
15+
16+
it('fibonacci of 25', () => {
17+
expect(fibonacci(25)).toBe(75025)
18+
})
19+
20+
it('Testing for invalid type', () => {
21+
expect(() => fibonacci('abc')).toThrowError()
22+
expect(() => fibonacci()).toThrowError()
23+
})
24+
})

0 commit comments

Comments
 (0)