Skip to content

Commit a710e64

Browse files
dev-madhurendramadhuredra
andauthored
feat : added fibonacci method using formula (TheAlgorithms#151)
* feat : added fibonacci method using formula * fix : test cases --------- Co-authored-by: madhuredra <[email protected]>
1 parent 4db3278 commit a710e64

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

maths/fibonacci.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,18 @@ export const nthFibonacciRecursively = (number: number): number => {
5656
nthFibonacciRecursively(number - 1) + nthFibonacciRecursively(number - 2)
5757
);
5858
};
59+
60+
61+
/**
62+
* @param number The index of the number in the Fibonacci sequence.
63+
* @return The Fibonacci number on the nth index in the sequence.
64+
* @example nthFibonacci(4) => 3 | nthFibonacci(6) => 8
65+
* @see : https://math.hmc.edu/funfacts/fibonacci-number-formula/
66+
* @author : dev-madhurendra<https://github.com/dev-madhurendra>
67+
*/
68+
69+
const sqrt5 = Math.sqrt(5)
70+
const phi = (1 + sqrt5) / 2
71+
const psi = (1 - sqrt5) / 2
72+
73+
export const nthFibonacciUsingFormula = (n : number) => Math.round((phi ** n - psi ** n) / sqrt5)

maths/test/fibonacci.test.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { nthFibonacci, nthFibonacciRecursively } from '../fibonacci';
1+
import { nthFibonacciUsingFormula, nthFibonacci, nthFibonacciRecursively } from '../fibonacci';
22

33
const test = (func: (n: number) => number) =>
44
it.each([
@@ -11,3 +11,4 @@ const test = (func: (n: number) => number) =>
1111
])('fib(%i) = %i', (n, expected) => expect(func(n)).toBe(expected));
1212
describe('Fibonacci iterative', () => test(nthFibonacci));
1313
describe('Fibonacci recursive', () => test(nthFibonacciRecursively));
14+
describe('Fibonacci Using formula', () => test(nthFibonacciUsingFormula));

0 commit comments

Comments
 (0)