Skip to content

Commit e652112

Browse files
authored
feature: add fast fibonacci algorithm (TheAlgorithms#1155)
1 parent 829d3fd commit e652112

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @function fastFibonacci
3+
* @description fastFibonacci is same as fibonacci algorithm by calculating the sum of previous two fibonacci numbers but in O(log(n)).
4+
* @param {Integer} N - The input integer
5+
* @return {Integer} fibonacci of N.
6+
* @see [Fast_Fibonacci_Numbers](https://www.geeksforgeeks.org/fast-doubling-method-to-find-the-nth-fibonacci-number/)
7+
*/
8+
9+
// recursive function that returns (F(n), F(n-1))
10+
const fib = (N) => {
11+
if (N === 0) return [0, 1]
12+
const [a, b] = fib(Math.trunc(N / 2))
13+
const c = a * (b * 2 - a)
14+
const d = a * a + b * b
15+
return N % 2 ? [d, c + d] : [c, d]
16+
}
17+
18+
const fastFibonacci = (N) => {
19+
if (!Number.isInteger(N)) {
20+
throw new TypeError('Input should be integer')
21+
}
22+
return fib(N)[0]
23+
}
24+
25+
export { fastFibonacci }
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { fastFibonacci } from '../FastFibonacciNumber'
2+
3+
describe('Testing FibonacciNumber', () => {
4+
const errorCases = ['0', '12', true]
5+
6+
test.each(errorCases)('throws an error if %p is invalid', (input) => {
7+
expect(() => {
8+
fastFibonacci(input)
9+
}).toThrow()
10+
})
11+
12+
const testCases = [
13+
[0, 0],
14+
[1, 1],
15+
[10, 55],
16+
[25, 75025],
17+
[40, 102334155]
18+
]
19+
20+
test.each(testCases)('if input is %i it returns %i', (input, expected) => {
21+
expect(fastFibonacci(input)).toBe(expected)
22+
})
23+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy