Skip to content

Commit 4d0d714

Browse files
algorithm: nth Fibonacci Number (#29)
* Initial commit * First commit * Delete .replit * Delete replit.nix * Delete index.ts * Delete .build directory * Update tsconfig.json * Changed Folder structure * Files updated * Fixed test cases and reduced spacing. * Fixed spacing * Changed the function name Fibonacci to nthFi onacci * Update Fibonacci.test.ts indentation fixed * Removed all blank lines
1 parent 781a0e7 commit 4d0d714

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

Maths/Fibonacci.ts

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* A function to get nth Fibonacci number
3+
* @param number The input integer
4+
* @return {number} Fibonacci number of `number`
5+
* @example nthFibonacci(4) => 3 | nthFibonacci(6) => 8
6+
* @see https://en.m.wikipedia.org/wiki/Fibonacci_number
7+
* @author MohdFaisalBidda <https://github.com/MohdFaisalBidda>
8+
*/
9+
10+
export const nthFibonacci = (number: number): number => {
11+
if (number < 0) throw "Number should be greater than 0";
12+
13+
if (number === 0) return 0;
14+
15+
let a = 0, b = 1;
16+
17+
for (let i = 1; i < number; ++i) {
18+
const c = a + b;
19+
20+
a = b;
21+
b = c;
22+
}
23+
24+
return b;
25+
};

Maths/test/Fibonacci.test.ts

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import {nthFibonacci} from '../Fibonacci';
2+
3+
describe('nthFibonacci', () => {
4+
test('should return correct value', () => {
5+
expect(nthFibonacci(0)).toBe(0);
6+
expect(nthFibonacci(1)).toBe(1);
7+
expect(nthFibonacci(5)).toBe(5);
8+
expect(nthFibonacci(4)).toBe(3);
9+
expect(nthFibonacci(0)).toBe(0);
10+
});
11+
});

0 commit comments

Comments
 (0)