2018-09-30 23:01:58 +01:00
|
|
|
---
|
|
|
|
title: Fibonacci sequence
|
|
|
|
id: 597f24c1dda4e70f53c79c81
|
|
|
|
challengeType: 5
|
2019-08-05 09:17:33 -07:00
|
|
|
forumTopicId: 302268
|
2018-09-30 23:01:58 +01:00
|
|
|
---
|
|
|
|
|
|
|
|
## Description
|
|
|
|
<section id='description'>
|
2019-06-14 20:04:16 +09:00
|
|
|
Write a function to generate the <code>n<sup>th</sup></code> Fibonacci number.
|
|
|
|
The <code>n<sup>th</sup></code> Fibonacci number is given by:
|
|
|
|
<code>F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub></code>
|
|
|
|
The first two terms of the series are 0 and 1.
|
2019-03-02 21:27:55 +09:00
|
|
|
Hence, the series is: 0, 1, 1, 2, 3, 5, 8, 13...
|
2018-09-30 23:01:58 +01:00
|
|
|
</section>
|
|
|
|
|
|
|
|
## Instructions
|
|
|
|
<section id='instructions'>
|
|
|
|
|
|
|
|
</section>
|
|
|
|
|
|
|
|
## Tests
|
|
|
|
<section id='tests'>
|
|
|
|
|
|
|
|
```yml
|
2018-10-04 14:37:37 +01:00
|
|
|
tests:
|
2019-11-20 07:01:31 -08:00
|
|
|
- text: <code>fibonacci</code> should be a function.
|
2019-07-26 05:24:52 -07:00
|
|
|
testString: assert(typeof fibonacci === 'function');
|
2018-10-04 14:37:37 +01:00
|
|
|
- text: <code>fibonacci(2)</code> should return a number.
|
2019-07-26 05:24:52 -07:00
|
|
|
testString: assert(typeof fibonacci(2) == 'number');
|
2020-03-10 15:43:41 +05:00
|
|
|
- text: <code>fibonacci(3)</code> should return 2.
|
|
|
|
testString: assert.equal(fibonacci(3),2);
|
|
|
|
- text: <code>fibonacci(5)</code> should return 5.
|
|
|
|
testString: assert.equal(fibonacci(5),5);
|
|
|
|
- text: <code>fibonacci(10)</code> should return 55.
|
|
|
|
testString: assert.equal(fibonacci(10),55);
|
2018-09-30 23:01:58 +01:00
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
</section>
|
|
|
|
|
|
|
|
## Challenge Seed
|
|
|
|
<section id='challengeSeed'>
|
|
|
|
|
|
|
|
<div id='js-seed'>
|
|
|
|
|
|
|
|
```js
|
|
|
|
function fibonacci(n) {
|
2020-09-15 09:57:40 -07:00
|
|
|
|
2018-09-30 23:01:58 +01:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</section>
|
|
|
|
|
|
|
|
## Solution
|
|
|
|
<section id='solution'>
|
|
|
|
|
|
|
|
|
|
|
|
```js
|
|
|
|
function fibonacci(n) {
|
|
|
|
let a = 0, b = 1, t;
|
2020-03-10 15:43:41 +05:00
|
|
|
while (--n >= 0) {
|
2018-09-30 23:01:58 +01:00
|
|
|
t = a;
|
|
|
|
a = b;
|
|
|
|
b += t;
|
|
|
|
}
|
|
|
|
return a;
|
|
|
|
}
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
</section>
|