BACK

Fibonacci Numbers

In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1.


This is a Memoization solution with runtime of (2n).

	
const memoFibonacci = (n, memo) => {
	memo = memo || {};
	// if memo[n] exists is has already been calculated, return it
	if (memo[n]) {
		return memo[n];   
	};
	// special cases, fib[0] = 0 and fib[1]=1
	if (n <= 1) {
		return n;
	}
	
	// memo[n] needs to be calutated if we get here
	let answer = memoFibonacci(n-1, memo) + memoFibonacci(n-2, memo);
	memo[n] = answer;

	return answer;
}
	


??

This is a recursive solution using no for or while loops, terrible runtime of (2^n). do Not go over 30 or it will take too long to process.

	
var recursiveFibonacci = function(n) {
	if ( n <= 1){
		return n;  
	} 
	let answer = recursiveFibonacci(n-1)+recursiveFibonacci(n-2);
	return answer;
};
	


??