Skip to content

Commit

Permalink
Nth fibonacci number exercise (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
soonick authored Aug 18, 2024
1 parent dd2101e commit cde3712
Show file tree
Hide file tree
Showing 4 changed files with 90 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Nth fibonacci number

The Fibonacci numbers are the numbers in the following integer sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

Given a number n, print n-th Fibonacci Number.

Examples:

```
Input: 0
Output: 0
Input: 1
Output: 1
Input: 2
Output: 1
Input: 3
Output: 2
Input: 9
Output: 34
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const assert = require('assert');

function nthFibonacciNumber(n) {
if (n == 0) {
return 0;
}

if (n == 1) {
return 1;
}

let secondLast = 0;
let last = 1;
let current = null;
for (let i = 1; i < n; i++) {
current = secondLast + last;
secondLast = last;
last = current;
}

return last;
}

assert.equal(nthFibonacciNumber(0), 0);
assert.equal(nthFibonacciNumber(1), 1);
assert.equal(nthFibonacciNumber(2), 1);
assert.equal(nthFibonacciNumber(3), 2);
assert.equal(nthFibonacciNumber(9), 34);

console.log("All assertions passed!");
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Nth fibonacci number

The Fibonacci numbers are the numbers in the following integer sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

Given a number n, print n-th Fibonacci Number.

Examples:

```
Input: 0
Output: 0
Input: 1
Output: 1
Input: 2
Output: 1
Input: 3
Output: 2
Input: 9
Output: 34
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const assert = require('assert');

function nthFibonacciNumber(n) {
}

assert.equal(nthFibonacciNumber(0), 0);
assert.equal(nthFibonacciNumber(1), 1);
assert.equal(nthFibonacciNumber(2), 1);
assert.equal(nthFibonacciNumber(3), 2);
assert.equal(nthFibonacciNumber(9), 34);

console.log("All assertions passed!");

0 comments on commit cde3712

Please sign in to comment.