Reputation: 9
I got this problem to calculate the time complexity?
const iterate = a => {
if (a === 5) {
return;
}
for (var i = 0; i <= a; i++) {
console.log(i);
iterate(i + 1);
}
};
iterate(0);
Upvotes: 0
Views: 350
Reputation: 386560
You get an infinite loop, because you increment the target value by one, but you start the for
statement with zero and this value does not change until it reaches the end of stack.
for (var i = 0; i <= a; i++) {
console.log(i);
iterate(i + 1);
}
That means, with the first zero value, you call the function again and this function calls itself again and so on.
The result is this uncatched error:
RangeError: Maximum call stack size exceeded
Upvotes: 1
Reputation: 68
Algorithm complexity is only defined for algorithms, which by (the most often accepted) definition must terminate.
The code above iterates for infinite number of times. So the time complexity of the code cannot be determined.
One may say O(n) where n=> infinity.
The above code doesnt stop since there is not condition on the value of 'i' which increases upto infinity.
Upvotes: 0