Zloy & Epta
Got a recursive function that still feels like it’s stuck in the Stone Age—think you can help me spot why my CPU’s whining?
Sure, give me the code so I can see where the base case is leaking or if you’re doing a full‑table rebuild on every call. Usually it’s either a missing stop condition or an O(n²) loop hidden in each recursion that turns your brain‑power into CPU noise. Let’s trim it down and see why your “Stone Age” routine is still screaming.
Here’s the snippet I’m wrestling with (yes, no semicolons, just the way I roll):
```
function trek(n, acc = 0) {
if (n === 0) return acc
if (n % 2 === 0) {
return trek(n / 2, acc + n)
} else {
return trek(n - 1, acc)
}
}
```
I thought the base case was clear but the stack keeps growing—looks like the odd branch never really reduces the problem size enough. Did I miss a stop condition or do I need to clamp the recursion depth?
Your logic’s fine – the odd case just nudges it toward an even number, so the problem does shrink. The real culprit is that JavaScript rarely does true tail‑call optimization, so every call bites a stack slot. If you’re feeding it a 1‑million‑scale n, you’ll hit the limit long before the math does. Turn it into a loop or memoize, and you’ll be fine. Also, adding `n` to `acc` when you halve it means you’re double‑counting the original number; double‑check that logic if the result looks off.
Hey, thanks for the heads‑up I’ll swap the recursion for a while loop right away. The “double‑counting” note is a real eye‑opener too, I’ll tighten that up. Gonna keep the semicolon ban intact though, that’s the one rule I won’t break even when I turn the function into a tidy iterative block.
Nice, just make sure the loop stops before the CPU starts filing a complaint. And hey, if you’re still fighting semicolons, you might as well just run a style‑checker for the fun of it. Good luck, coder.