Problem statement
Write a function fibonacci(n) that takes a positive integer n as input and returns the nth number in the Fibonacci sequence. The Fibonacci sequence is a series of numbers in which each number after the first two is the sum of the two preceding ones. The sequence starts with 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.
Constraints
The input integer n will be a positive integer not exceeding 50.
Notes
This problem can be solved using recursion, but using an iterative solution is also a valid approach.
function fibonacci(n) {
if (n === 0) {
return 0;
}
if (n === 1) {
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
const { expect } = require('chai');
describe('fibonacci', function() {
it('should return 0 for input 0', function() {
expect(fibonacci(0)).to.equal(0);
});
it('should return 1 for input 1', function() {
expect(fibonacci(1)).to.equal(1);
});
it('should return 1 for input 2', function() {
expect(fibonacci(2)).to.equal(1);
});
it('should return 2 for input 3', function() {
expect(fibonacci(3)).to.equal(2);
});
it('should return 55 for input 10', function() {
expect(fibonacci(10)).to.equal(55);
});
});