The pseudocode for incrementing natural numbers using a recursive algorithm is like this (example from the Algorithm Design Manual by Steven S. Skiena):
Increment(y)
if y = 0 then return(1) else
if (y mod 2) = 1 then
return(2 * Increment(y/2))
else return(y + 1)
I implemented it with JavaScript here: https://repl.it/@danielmai/IncrementalNaturalNumbers
function increment(y) {
if(y == 0) return 1
if(y % 2 == 1) {
return 2 * increment(y / 2)
}
else return y + 1
}
It doesn't work for odd numbers. I found out that JavaScript rounds up numbers with 0.5 or higher, so if y is odd, it will increment twice, i.e 5 -> 7.
I can use Math.floor(y/2) to make it round down, but I assume this function should work regardless of rounding up or down. So my question is, is there a way to correct this recursive function in JS without using Math.floor?