var num = [1,1];
var total = 0;
var i = num.length;
do {
i++;
num[i] = num[num.length-1] + num[num.length-2];
total+=num[i];
console.log(total);
}
while(num[num.length] < 4000000);
I’ve been working on the Project Euler questions for a day or two now to hopefully expand my knowledge and usefulness. On the second question I’ve been figuring out a (bad) way to get the fibonacci sequence. However my code will print “2” to console as it SHOULD but then stopping. Another issue I have is that just using the “while(X IS TRUE/FALSE) { DO STUFF }” just won’t work. Not a clue why.
I’m probably just making dumb mistakes but somebody please enlighten me 🙂
Your
numarray has 2 elements, thereforenum.length(and alsoi) are 2. The 1st statement in yourdoblock isi++. Nowiis 3.You’re setting
num[3], which meansnumis now[1, 1, undefined, 1].Also, in your
while, you are checkingnum[num.length]. Since arrays are zero-indexed, this will never work, asnum.lengthis now 4.What I suggest is: increment
iafter setting the element. So, you push a new element, then increment the length counter.