patternjavascriptModerate
Find fibonacci series upto a given maximum in javascript
Viewed 0 times
maximumfibonaccijavascriptuptofindseriesgiven
Problem
I'm attempting to find a fibonacci series where the last number is no greater than a given maximum. Given the start digits
Here's my working code.
1, 2Here's my working code.
var fib = [1,2];
var max = 4000000;
var i = 2;
var loop = true
while (loop) {
if (fib[i-1] + fib[i-2] > max) {
loop = false;
} else {
fib.push(fib[i-1] + fib[i-2]);
i++;
}
}
console.log(fib)Solution
Your loop can be terminated in a few different ways. You're using a boolean
One is to simply move the
Another is to keep the
Here we avoid calculating the new fibonacci number twice, but still: the previous code block is probably still the cleanest.
You also initialize
Lastly, it might be good to consider "bad" max values. I.e. what if the maximum is set to zero? Or 1? Or -2324359? For zero you could return an empty array; for 1 you'd need to return a shorter array than what you start with, and for the negative max you could throw an error or return null. Not saying you need to any of this, but it's always to good to consider how you handle such cases.
loop variable, but there are cleaner ways.One is to simply move the
if condition to the while condition (Malachi's answer beat me to this):while (fib[i-1] + fib[i-2] <= max) {
i = fib.push(fib[i-1] + fib[i-2]);
}push helpfully returns the array's new length, so you don't need the i++.Another is to keep the
if branching, but use it to break the loop instead:while (true) {
var next = fib[i-1] + fib[i-2];
if (next > max) {
break; // exit the loop
}
i = fib.push(next);
}Here we avoid calculating the new fibonacci number twice, but still: the previous code block is probably still the cleanest.
You also initialize
i to 2, which is a bit redundant: It's the length of the fib array. Rather than manually initializing the array, and manually recording its length, I'd just do var i = fib.length.Lastly, it might be good to consider "bad" max values. I.e. what if the maximum is set to zero? Or 1? Or -2324359? For zero you could return an empty array; for 1 you'd need to return a shorter array than what you start with, and for the negative max you could throw an error or return null. Not saying you need to any of this, but it's always to good to consider how you handle such cases.
Code Snippets
while (fib[i-1] + fib[i-2] <= max) {
i = fib.push(fib[i-1] + fib[i-2]);
}while (true) {
var next = fib[i-1] + fib[i-2];
if (next > max) {
break; // exit the loop
}
i = fib.push(next);
}Context
StackExchange Code Review Q#155595, answer score: 10
Revisions (0)
No revisions yet.