mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 00:01:37 +08:00
added fibonacci using formula along with test cases (#1358)
* 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 <madhuredra.tiwari@zemosolabs.com> Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
This commit is contained in:

committed by
GitHub

parent
9757e2bee3
commit
268796b0e8
@ -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 }
|
||||
|
@ -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)
|
||||
})
|
||||
})
|
||||
|
Reference in New Issue
Block a user