6 kyu · algorithms

Complete Fibonacci Series

Algorithms

The function 'fibonacci' should return an array of fibonacci numbers. The function takes a number as an argument to decide how many no. of elements to produce. If the argument is less than or equal to 0 then return empty array

Example:

fibonacci(4) // should return  [0,1,1,2]
fibonacci(-1) // should return []
fibonacci(4); # should return  [0,1,1,2]
fibonacci(-1); # should return []
fibonacci(4) # should return  [0,1,1,2]
fibonacci(-1) # should return []

Solutions

01-solution.jsView on GitHub ↗
function fibonacci(n) {
	const res = [];

	let cn = 0,
		an = 1,
		nextTerm;

	for (let i = 1; i <= n; i += 1) {
		res.push(cn);
		nextTerm = cn + an;
		cn = an;
		an = nextTerm;
	}

	return res;
}