Skip to content

algorithm: nth Fibonacci Number #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 16 commits into from
Oct 7, 2022
Merged
25 changes: 25 additions & 0 deletions Maths/Fibonacci.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* A function to get nth Fibonacci number
* @param number The input integer
* @return {number} Fibonacci number of `number`
* @example nthFibonacci(4) => 3 | nthFibonacci(6) => 8
* @see https://en.m.wikipedia.org/wiki/Fibonacci_number
* @author MohdFaisalBidda <https://github.com/MohdFaisalBidda>
*/

export const nthFibonacci = (number: number): number => {
if (number < 0) throw "Number should be greater than 0";

if (number === 0) return 0;

let a = 0, b = 1;

for (let i = 1; i < number; ++i) {
const c = a + b;

a = b;
b = c;
}

return b;
};
11 changes: 11 additions & 0 deletions Maths/test/Fibonacci.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {nthFibonacci} from '../Fibonacci';

describe('nthFibonacci', () => {
test('should return correct value', () => {
expect(nthFibonacci(0)).toBe(0);
expect(nthFibonacci(1)).toBe(1);
expect(nthFibonacci(5)).toBe(5);
expect(nthFibonacci(4)).toBe(3);
expect(nthFibonacci(0)).toBe(0);
});
});