Good morning! Here's our prompt for today.
Implement a function that returns the Fibonnaci
number for a given integer input. In a Fibonacci sequence, each number is the sum of the two preceding ones.
The simplest is the series: 1, 1, 2, 3, 5, 8, etc.
This is because:
SNIPPET
1fibonacci(0) = 0
2fibonacci(1) = 1
3fibonacci(2) = 1
4fibonacci(3) = 1 + 1 = 2
5fibonacci(4) = 1 + 2 = 3
6fibonacci(5) = 2 + 3 = 5
So if we were to invoke fibonacci(5)
, we'd want to return 5
(because the second to last number was 2
+ last number was 3
).
Constraints
- The value of
n
will always be a non negative integer and<=40
- The answer is guaranteed to fit in the integer data type
- Expected time and space complexity are both
O(n)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
36
console.log('PASSED: ' + '`fibonacci(34)` should return `5702887`');
var assert = require('assert');
​
/*
* @param {number} n The Fibonacci number to get.
* @returns {number} The nth Fibonacci number
*/
​
function fibonacci(num) {
// fill this in
return num;
}
​
try {
assert.equal(fibonacci(1), 1);
​
console.log('PASSED: ' + '`fibonacci(1)` should return `1`');
} catch (err) {
console.log(err);
}
​
try {
assert.equal(fibonacci(17), 1597);
​
console.log('PASSED: ' + '`fibonacci(17)` should return `1597`');
} catch (err) {
console.log(err);
}
​
try {
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's how we would solve this problem...
How do I use this guide?