<div>
<p>
In the Fibonnaci sequence, each following number is the sum of its previous 2 numbers. The first few values in the Fibonnaci sequence are [0,1,1,2,3,5,8]
<br>
<br>
Write a function that outputs answers to the Fibonnoci sequence when called with an input.
<br><br>
<i>i.e. <br>fib(6)=8<br>fib(0)=0<br>fib(36)=??</i>
</p>
</div>
JavaScript
var fib = function(test)
{
if(test == 0) return 0;
if(test == 1) return 1;
return fib(test-1) + fib(test-2);
}
console.log(fib(8));
////
var fibArray = [0,1]
function fib(__input){
//check to see if it exists
if(fibArray[__input] == null){
var prev1 = fibArray[fibArray.length-1];
var prev2 = fibArray[fibArray.length-2];
//add the two previous numbers and extend array
fibArray.push(prev1+prev2);
//recursion, call it again untill there's an answer
return fib(__input);
} else {
return fibArray[__input];
}
}
console.log(fib(6));
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.