javascript - How to return the sum of the two previous numbers? - Stack Overflow

I want to write a function that returns a number based on the fibonacci rule where each new number retu

I want to write a function that returns a number based on the fibonacci rule where each new number returned is based on the sum of the two previous numbers 1, 1, 2, 3, 5, etc. So if the user inputs 4, the output should be 3. And it should work with any number such as 10, 12, 45, etc.

I tried using for loop to create an array but didn't get the results as I had expected. When i++ >= 3 I get NaN instead of 3.

const fibonacci = function(num) {
  for (let i = 2; i < num; i++) {

    let arr = [0, 1, 1];
    let num1 = arr[i];
    let num2 = arr[i - 1];
    let push;

    push = arr.push(num1 + num2);
    console.log(arr);
  }
};

fibonacci(4);

I want to write a function that returns a number based on the fibonacci rule where each new number returned is based on the sum of the two previous numbers 1, 1, 2, 3, 5, etc. So if the user inputs 4, the output should be 3. And it should work with any number such as 10, 12, 45, etc.

I tried using for loop to create an array but didn't get the results as I had expected. When i++ >= 3 I get NaN instead of 3.

const fibonacci = function(num) {
  for (let i = 2; i < num; i++) {

    let arr = [0, 1, 1];
    let num1 = arr[i];
    let num2 = arr[i - 1];
    let push;

    push = arr.push(num1 + num2);
    console.log(arr);
  }
};

fibonacci(4);

Share edited Mar 3 at 20:14 isherwood 61.2k16 gold badges121 silver badges170 bronze badges asked Mar 3 at 20:05 lunarchildlunarchild 256 bronze badges 4
  • 5 let arr = [0, 1, 1]; is created for every iteration of the loop. It's not persistent. Pill it out of the loop. – VLAZ Commented Mar 3 at 20:07
  • 1 If you used a debugger, you would have solved the problem during the time less than the time you've spent on publishing of this question. – Sergey A Kryukov Commented Mar 3 at 20:14
  • 1 Protip: Your first three inner variables can be constants (using const) here. – isherwood Commented Mar 3 at 20:15
  • 1 What's the reason for the push variable? You never use it. – Barmar Commented Mar 3 at 20:45
Add a comment  | 

3 Answers 3

Reset to default 1

The problem in your fibonnaci function is that you are declaring arr inside the for loop. For instance, you are creating a new array on each iteration and thus the index i will be NaN pass the first 3 elements.

const fibonacci = function (num) {
  let arr = [0, 1, 1]; // Declare before for loop

  for (let i = 2; i < num; i++) {
    let num1 = arr[i];
    let num2 = arr[i - 1];
    arr.push(num1 + num2); 
    console.log(arr);
  }
};

fibonacci(4);

a big classic...

console.log( '  4   ->', JSON.stringify( fibonacci(4)   ) );
console.log( '  8   ->', JSON.stringify( fibonacci(8)   ) );
console.log( '  2.2 ->', JSON.stringify( fibonacci(2.2) ) );
console.log( '-58   ->', JSON.stringify( fibonacci(-58) ) );
console.log( '"x"   ->', JSON.stringify( fibonacci("x") ) );

function fibonacci(num = 4)
  {
  num = isNaN(num) ? 0 : Math.max( 0,parseInt(num)) // positive int only
    ;
  let arr = [0, 1, 1]  // Fibonacci priming [is not inside a loop]
    ; 
  for (let i = 2; i < num; i++)
    arr.push( arr[i] + arr[i - 1] )
    ;  
  return arr.slice(0, num)
  }

function fibonacciDP(n) {
    // Validate input
    if (typeof n !== 'number' || !Number.isInteger(n) || n < 0) {
        return NaN; // Handle invalid input
    }

    // Base cases
    if (n === 0) return 0;
    if (n === 1) return 1;

    // Create an array to store Fibonacci numbers up to n
    const fibArray = new Array(n + 1);
    fibArray[0] = 0; // F(0)
    fibArray[1] = 1; // F(1)

    // Fill the array using the previous two values
    for (let i = 2; i <= n; i++) {
        fibArray[i] = fibArray[i - 1] + fibArray[i - 2];
    }

    return fibArray[n]; // Return the nth Fibonacci number  
}

As you can see the array is defined before the loop. For your code to work:

const fibonacci = function(num) {
    let arr = [0, 1, 1];
    for (let i = 2; i < num; i++) {
      let num1 = arr[i];
      let num2 = arr[i - 1];
      let push;

      push = arr.push(num1 + num2);
      console.log(arr);
    }
    return arr[num];
};

console.log(fibonacci(4));

It is classic example of dynamic programming. you can follow below link for better understanding, https://www.geeksfeeks./program-for-nth-fibonacci-number/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745074459a4609749.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信