Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
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))
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!