Skip to content

Commit

Permalink
added fibonacci using formula along with test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
madhuredra committed Sep 11, 2023
1 parent 00e40e6 commit 186dcb7
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
19 changes: 19 additions & 0 deletions Maths/FibonacciUsingFormula.js
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 };
28 changes: 28 additions & 0 deletions Maths/test/FibonacciUsingFormula.test.js
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)
})
})

0 comments on commit 186dcb7

Please sign in to comment.