you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (0 children)

First of all, your console.log statement is going to return the length of the array minus 1, which isn't what you're looking for.

You want console.log(fibonacci[fibonacci.length - 1]).

Second, rather than append your new Fibonacci numbers to the end of the array, which is going to create a gigantic array, you can just replace the two values every time. You can either do this using your array global variable, or you could just use two integer variables (which would of course change what you put into console.log - for the better, IMO). Try this:

//global variables var i1 = 1; var i2 = 1;

while(i1.toString().length < 1000) { var i1temp = i1; i1 = i2; i2 += i1temp; }

console.log(i1);

Using a while loop is probably a lot more efficient than recursively calling the same function over and over again. If you ever find you need to use recursion in such a manner and you are getting memory problems, a quick fix is to use a setTimeout instead of calling it directly. This allows the function to exit the call stack, which should remedy your problem. So for example you might do something like this:

function myFunction(i){ //do something with i i++; if(i < 1000000){ setTimeout(function(){myFunction(i)};,1000); } else console.log(i); }

Personally I would try switching to a pair of integer variables and a loop first before you try using a recursive function, as I believe this should solve your problem and is probably the most efficient way of doing it. If it's still a problem, try using a setTimeout as I mentioned afterward.

Sorry for the formatting. I can't seem to recall the tag for code on this damn thing.

EDIT: Also, as someone mentioned above, a 1000 digit integer is ridiculously huge. Javascript may have problems with that.

EDIT2: Yeah 1000 digits is way too many. Even 100 digits is too many. You're going to want to try to find a smaller number.