Skip to content
Advertisement

How to find nth Fibonacci number using Javascript with O(n) complexity

Trying really hard to figure out how to solve this problem. The problem being finding nth number of Fibonacci with O(n) complexity using javascript.

I found a lot of great articles how to solve this using C++ or Python, but every time I try to implement the same logic I end up in a Maximum call stack size exceeded.

Example code in Python

JavaScript

Then trying to port this to Javascript

JavaScript

That obviously doesn’t work. In Javascript this ends up in an infinite loops. So how would you solve this using Javascript?

Thanks in advance

Advertisement

Answer

The problem is related to scope of the k variable. It must be inside of the function:

JavaScript

You can find far more good implementations here list

DEMO

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement