Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Fibonacci Sequence

var x = 0; var y = 1; var z;  fib[0] = 0; fib[1] = 1;  for (i = 2; i <= 10; i++) {   alert(x + y);   fib[i] = x + y;   x = y;   z = y; } 

I'm trying to get to generate a simple Fibonacci Sequence but there no output.

Can anybody let me know what's wrong?

like image 224
methuselah Avatar asked Oct 30 '11 09:10

methuselah


People also ask

How can we generate Fibonacci sequence?

The Fibonacci series is formed by starting with 0 and 1 and then adding the latest two numbers to get the next one: 0 1 --the series starts like this. 0+1=1 so the series is now 0 1 1 1+1=2 so the series continues... 0 1 1 2 and the next term is 1+2=3 so we now have 0 1 1 2 3 and it continues as follows ...

What is Fibonacci series generator?

A Lagged Fibonacci generator (LFG or sometimes LFib) is an example of a pseudorandom number generator. This class of random number generator is aimed at being an improvement on the 'standard' linear congruential generator. These are based on a generalisation of the Fibonacci sequence.


2 Answers

You have never declared fib to be an array. Use var fib = []; to solve this.

Also, you're never modifying the y variable, neither using it.

The code below makes more sense, plus, it doesn't create unused variables:

var i;  var fib = []; // Initialize array!    fib[0] = 0;  fib[1] = 1;  for (i = 2; i <= 10; i++) {    // Next fibonacci number = previous + one before previous    // Translated to JavaScript:    fib[i] = fib[i - 2] + fib[i - 1];    console.log(fib[i]);  }
like image 187
Rob W Avatar answered Sep 23 '22 11:09

Rob W


According to the Interview Cake question, the sequence goes 0,1,1,2,3,5,8,13,21. If this is the case, this solution works and is recursive without the use of arrays.

function fibonacci(n) {    return n < 1 ? 0         : n <= 2 ? 1         : fibonacci(n - 1) + fibonacci(n - 2) }  console.log(fibonacci(4)) 

Think of it like this.

   fibonacci(4)   .--------> 2 + 1 = 3       |          /               |       '--> fibonacci(3) + fibonacci(2)             |    ^                        |    '----------- 2 = 1 + 1 <----------. 1st step -> |                     ^                |             |                     |                |             '---->  fibonacci(2) -' + fibonacci(1)-' 

Take note, this solution is not very efficient though.

like image 36
Alex Cory Avatar answered Sep 20 '22 11:09

Alex Cory