Skip to content
Advertisement

Stop fibonacci sequence when it reaches a number bigger than 1000

I want to make the sequence stop when the last value stored in the array is bigger than 1000.

I have the js code for the sequence and i can make it stop at whatever position i want with the variable limit. But i dont know how to make it stop at a certain number.

The is my code:

let fib = [1,1];
let limit = 20;

function fibonacci(nums) {
    let data = [1,1];
    
    for(let i = 2; i < limit; i++) {
      nums[i] = nums[i - 1] + nums[i - 2];
      data.push(nums[i]);
    }
      
    return data;
      

}

  console.log(fibonacci(fib))

Advertisement

Answer

You can just use an if condition and break out of the loop as soon as a value is bigger than 1000. In this example I pushed the value and then break out of the loop. You can also break before pushing it to the array

let fib = [1, 1];
let limit = 20;

function fibonacci(nums, breakLimit) {
  let data = [1, 1];

  for (let i = 2; i < limit; i++) {
    nums[i] = nums[i - 1] + nums[i - 2];
    if (nums[i] > breakLimit) {
      data.push(nums[i]);
      break;
    } else {
      data.push(nums[i]);
    }
  }
  return data;
}

console.log(fibonacci(fib, 1000))
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement