-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
added fibonacci using formula along with test cases
- Loading branch information
madhuredra
committed
Sep 11, 2023
1 parent
00e40e6
commit 186dcb7
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
// https://en.wikipedia.org/wiki/Fibonacci_sequence | ||
|
||
/* | ||
Nth Fibonacci Number : | ||
Fn = (((1+sqrt(5))^n) - ((1-sqrt(5))^n))/(2^n)*sqrt(5) | ||
Complexities : | ||
TC - O(1) | ||
SC - O(1) | ||
*/ | ||
const FibonacciUsingFormula = (n) => { | ||
const sqrt5 = Math.sqrt(5); | ||
const phi = (1 + sqrt5) / 2; | ||
const psi = (1 - sqrt5) / 2; | ||
const result = (Math.pow(phi, n) - Math.pow(psi, n)) / sqrt5; | ||
return Math.round(result); | ||
} | ||
|
||
export { FibonacciUsingFormula }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import { FibonacciUsingFormula } from '../FibonacciUsingFormula' | ||
|
||
describe('FibonacciUsingFormula' , () => { | ||
it('should calculate the correct Fibonacci number for n = 0', () => { | ||
const result = FibonacciUsingFormula(0) | ||
expect(result).toBe(0) | ||
}) | ||
it('should calculate the correct Fibonacci number for n = 1', () => { | ||
const result = FibonacciUsingFormula(1) | ||
expect(result).toBe(1) | ||
}) | ||
it('should calculate the correct Fibonacci number for n = 2', () => { | ||
const result = FibonacciUsingFormula(2) | ||
expect(result).toBe(1) | ||
}) | ||
it('should calculate the correct Fibonacci number for n = 5', () => { | ||
const result = FibonacciUsingFormula(5) | ||
expect(result).toBe(5) | ||
}) | ||
it('should calculate the correct Fibonacci number for n = 10', () => { | ||
const result = FibonacciUsingFormula(10) | ||
expect(result).toBe(55) | ||
}) | ||
it('should calculate the correct Fibonacci number for n = 15', () => { | ||
const result = FibonacciUsingFormula(15) | ||
expect(result).toBe(610) | ||
}) | ||
}) |