Skip to content

Commit 268796b

Browse files
dev-madhurendramadhuredraappgurueu
authored
added fibonacci using formula along with test cases (TheAlgorithms#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>
1 parent 9757e2b commit 268796b

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

Maths/Fibonacci.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,9 +187,20 @@ const FibonacciMatrixExpo = (num) => {
187187
return F[0][0] * (isNeg ? (-ONE) ** (num + ONE) : ONE)
188188
}
189189

190+
/*
191+
Resource : https://math.hmc.edu/funfacts/fibonacci-number-formula/
192+
*/
193+
194+
const sqrt5 = Math.sqrt(5)
195+
const phi = (1 + sqrt5) / 2
196+
const psi = (1 - sqrt5) / 2
197+
198+
const FibonacciUsingFormula = n => Math.round((phi ** n - psi ** n) / sqrt5)
199+
190200
export { FibonacciDpWithoutRecursion }
191201
export { FibonacciIterative }
192202
export { FibonacciGenerator }
193203
export { FibonacciRecursive }
194204
export { FibonacciRecursiveDP }
195205
export { FibonacciMatrixExpo }
206+
export { FibonacciUsingFormula }

Maths/test/Fibonacci.test.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ import {
44
FibonacciIterative,
55
FibonacciGenerator,
66
FibonacciRecursive,
7-
FibonacciMatrixExpo
7+
FibonacciMatrixExpo,
8+
FibonacciUsingFormula
89
} from '../Fibonacci'
910

1011
describe('Fibonacci', () => {
@@ -95,4 +96,11 @@ describe('Fibonacci', () => {
9596
expect(FibonacciMatrixExpo(-5n)).toBe(5n)
9697
expect(FibonacciMatrixExpo(-6n)).toBe(-8n)
9798
})
99+
it.each([
100+
[0, 0],
101+
[1, 1],
102+
[15, 610]
103+
])('should calculate the correct Fibonacci number for n = %i', (n, expected) => {
104+
expect(FibonacciUsingFormula(n)).toBe(expected)
105+
})
98106
})

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