Fibonacci series in JavaScript
Asked Answered
O

17

10

function fib(n) {

  const result = [0, 1];
  for (var i = 2; i <= n; i++) {
    const a = (i - 1);
    const b = (i - 2);
    result.push(a + b);
  }
  return result[n];

}

console.log(fib(8));

The output of the code above is 13. I don't understand the for loop part. In very first iteration i = 2, but after second iteration i = 3 so a = 2 and b = 1 and third iteration i = 4 so a = 3, b = 2, and so on... If it's going on final sequence will be : [0, 1, 1, 3, 5, 7, 9, 11], which is incorrect. The correct sequence will be [0, 1, 1, 2, 3, 5, 8, 13]

Overturn answered 30/6, 2018 at 4:59 Comment(3)
What do you want to return? result or result[n]?Subcutaneous
You are not using the previous two numbers to generate the new number.Subcutaneous
Please remember that you can and should accept an answer if the problem is solved - Thanks!Insult
S
9

You were not using the previous two numbers that are already in the array to > generate the new fibonacci number to be inserted into the array.

https://www.mathsisfun.com/numbers/fibonacci-sequence.html

Here I have used the sum of result[i-2] and result[i-1] to generate the new fibonacci number and pushed it into the array.

Also to generate n number of terms you need the condition to be i < n and not i <= n.

function fib(n) {

  const result = [0, 1];
  for (var i = 2; i < n; i++) {
    result.push(result[i-2] + result[i-1]);
  }
  return result; // or result[n-1] if you want to get the nth term

}

console.log(fib(8)); 

Return result[n-1] if you want to get the nth term.

Subcutaneous answered 30/6, 2018 at 5:3 Comment(0)
W
5

My solution for Fibonacci series:

 const fibonacci = n =>
      [...Array(n)].reduce(
        (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
        []
      )
Weiler answered 19/4, 2019 at 15:18 Comment(0)
B
2

This function is incorrect. It cat be checked by just adding the console.log call just before the function return:

function fib(n) {

  const result = [0, 1];
  for (var i = 2; i <= n; i++) {
    const a = (i - 1);
    const b = (i - 2);
    result.push(a + b);
  }
  console.log(result);
  return result[n];

}

console.log(fib(7));

As you can see, the sequence is wrong and (for n = 7) the return value is too.

The possible change would be as following:

function fib(n) {

  const result = [0, 1];
  for (var i = 2; i <= n; i++) {
    const a = result[i - 1];
    const b = result[i - 2];
    result.push(a + b);
  }
  console.log(result);
  return result[n];

}

console.log(fib(8));

This is the "classical" Fibonacci numbers; if you really want to use the first number of 0, not 1, then you should return result[n-1], since array indexes start from zero.

Baptlsta answered 30/6, 2018 at 5:6 Comment(0)
K
2

One approach you could take for fibonacci sequence is recursion:

var fibonacci = {
  getSequenceNumber: function(n) {
    //base case to end recursive calls
    if (n === 0 || n === 1) {
      return this.cache[n];
    }

    //if we already have it in the cache, use it
    if (this.cache[n]) {
      return this.cache[n];
    }
    //calculate and store in the cache for future use
    else {
      //since the function calls itself it's called 'recursive'
      this.cache[n] = this.getSequenceNumber(n - 2) + this.getSequenceNumber(n - 1);
    }

    return this.cache[n];
  },

  cache: {
    0: 0,
    1: 1
  }
}
//find the 7th number in the fibbonacci function
console.log(fibonacci.getSequenceNumber(7));

//see all the values we cached (preventing extra work)
console.log(fibonacci.cache);

//if you want to output the entire sequence as an array:
console.log(Object.values(fibonacci.cache));

The code above is also an example of a dynamic programming approach. You can see that I am storing each result in a cache object the first time it is calculated by the getSequenceNumber method. This way, the second time that getSequenceNumber is asked to find a given input, it doesn't have to do any actual work - just grab the value from cache and return it! This is an optimization technique that can be applied to functions like this where you may have to find the value of a particular input multiple times.

Ketone answered 30/6, 2018 at 14:2 Comment(0)
S
1

What you are doing wrong is adding the iterator index (i), whereas what you need to do is add the element in the result at that index.

function fib(n) {

  const result = [0, 1];

  for (let i = 2; i <= n; i++) {
    const a = result[(i - 1)];
    const b = result[(i - 2)];
    result.push(a + b);
  }
  console.log("Result Array: " + result);
  return result[n];

}

console.log("Fibonacci Series element at 8: " + fib(8));
Steiner answered 30/6, 2018 at 5:4 Comment(0)
S
1

const fib = n => {
  const array = Array(n);
  for (i = 0; i < array.length; i++) {
    if (i > 1) {
      array[i] = array[i - 1] + array[i - 2];
    } else {
      array[i] = 1;
    }
  }
  return array;
}

console.log(fib(5))
Storehouse answered 24/5, 2019 at 3:53 Comment(0)
L
0

There are two issues with the logic:

  1. Variables a and b currently refer to i - 1 and i - 2. Instead they should refer to the elements of result array, i.e. result[i - 1] and result[i - 2].

  2. If you need 8th element of the array, you need to call result[7]. So the returned value should be result[n - 1] instead of result[n].

function fib(n) {

  const result = [0, 1];
  for (var i = 2; i < n; i++) {
    const a = result[i - 1];
    const b = result[i - 2];
    result.push(a + b);
  }
  
  console.log(result);
  return result[n - 1];
}

console.log(fib(8));
Laurinelaurita answered 30/6, 2018 at 5:5 Comment(0)
E
0

simple solution for Fibonacci series:

function fib(n){
    var arr = [];
    for(var i = 0; i <n; i++ ){
        if(i == 0 || i == 1){
            arr.push(i);
        } else {
            var a = arr[i - 1];
            var b = arr[i - 2];
            arr.push(a + b);
        }
    }
    return arr
}
console.log(fib(8))
Edger answered 31/10, 2018 at 9:16 Comment(0)
F
0

This is certainly one of those "more than one way to clean chicken" type situations, this JavaScript method below works for me.

function fibCalc(n) {
    var myArr = [];

    for (var i = 0; i < n; i++) {
        if(i < 2) {
            myArr.push(i);
        } else {
            myArr.push(myArr[i-2] + myArr[i-1]);
        }
    } 

    return myArr;
}

fibCalc(8);

When called as above, this produces [0,1,1,2,3,5,8,13] It allows me to have a sequence of fib numbers based on n.

Fatherly answered 23/5, 2019 at 23:26 Comment(0)
R
0
function fib(n) {
    const result = [0];

    if (n > 1) {
        result.push(1);

        for (var i = 2; i < n; i++) {
            const a = result[result.length - 1]
            const b = result[result.length - 2];
            result.push(a + b);
        }

    }
    console.log(result);
}
Reggi answered 6/8, 2019 at 10:11 Comment(1)
Could you explain why this is an improvement?Gillan
J
0

i came up with this solution to get the n index fibonacci value.

function findFac(n){
if (n===1) 
  {
   return [0, 1];
  } 
  else 
  {
    var s = findFac(n - 1);
    s.push(s[s.length - 1] + s[s.length - 2]);
    return s;
  }
}

function findFac0(n){
var vv1 = findFac(n);
return vv1[n-1];
}


console.log(findFac0(10));
Jeopardy answered 7/8, 2019 at 5:44 Comment(0)
P
0

Here, you have it, with few argument check, without using exception handling

function fibonacci(limit){
    if(typeof limit != "number"){return "Please enter a natural number";}

    if(limit <=0){
        return "limit should be at least 1";
    }
    else if(limit == 1){
        return [0];
    }
    else{
        var series = [0, 1];
        for(var num=1; num<=limit-2; num++){
            series.push(series[series.length-1]+series[series.length-2]);
        }
        return series;
    }
}
Preconcerted answered 23/9, 2019 at 9:0 Comment(0)
H
0

I came up with this solution.

function fibonacci(n) {
    if (n == 0) {
        return [0];
    }
    if ( n == 1) {
        return [0, 1];
    } else {
        let fibo = fibonacci(n-1);
        let nextElement = fibo [n-1] + fibo [n-2];
        fibo.push(nextElement);
        return fibo;
    }
}
console.log(fibonacci(10));
Hilariahilario answered 18/6, 2021 at 7:25 Comment(0)
T
0
function fibonacciGenerator (n) {
 var output = [];
  if(n===1){
    output=[0];
  }else if(n===2){
    output=[0,1];    
  }else{
    output=[0,1];
    for(var i=2; i<n; i++){
      output.push(output[output.length-2] + output[output.length-1]);
    }
  }
  return output;
}
output = fibonacciGenerator();
console.log(output);
Tarry answered 2/6, 2022 at 15:4 Comment(2)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Celebrated
Answer could do with some amount of explanation, especially to stand out from the other 13 answersCento
H
0
function fibonacci(end) {
    if (isNaN(end) === false && typeof (end) === "number") {
        var one = 0, res, two = 1;
        for (var i = 0; i < end; ++i) {
            res = one + two;
            one = two;
            two = res;
            console.log(res);
        }
    } else {
        console.error("One of the parameters is not correct!")
    }
}

fibonacci(5);
Hen answered 26/6, 2022 at 16:37 Comment(0)
N
0
     var input = parseInt(prompt(""));
     var a =0;
     var b=1;
     var x;
     for(i=0;i<=input;i++){
        document.write(a+"<br>")
        x = a+b;
        a =b;
        b= x;
     }
Nomarchy answered 2/12, 2022 at 18:21 Comment(1)
I think this one is easier for beginners.Nomarchy
L
0

if you don't want to use recursion neither array in memory to compute Fibonacci(n) you can do like this

function fibonacci(n) { 
    return Math.round((Math.pow((1 + Math.sqrt(5))/2,n) - (Math.pow(2/(1 + Math.sqrt(5)),n) * (Math.cos(n*Math.PI))))/Math.sqrt(5)); 
}

proof: wolframalpha closed form of Fibonacci

if you want then to compute bigger fibonacci(n), because of limitation of integer type in javascript, you have to use a library like Math.js to handle cosine and round and sqrt for BigInt (aka BigNumbers in Math.js) if not you have to use BigInteger type, for pow you can use ** but for sqrt, round and cos, you have to create your own methods..

Laoag answered 14/12, 2023 at 21:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.