1

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?

1
  • 1
    Javascript has no integer division, so no. Commented Jun 7, 2018 at 18:17

2 Answers 2

2

This has nothing to do with javascript rounding numbers up with 0.5 or higher.

Your increment function is asuming x / 2 will return an integer, but in javascript this will give a decimal number when odd. So when doing increment(3), you are recursively calling increment(1.5). As 1.5 % 2 = 1.5, its not == 1 so it ends up returning 2.5. So in the end, you end up returning 2.5 * 2 = 5.

This funcion would indeed work on c++ where if you are working with integers, division will trim trailing decimals. However, in javascript addition +, subtraction -, multiplication *, division /, power **, and modulo % all treat numbers in JavaScript as a double. Only binary operators treat numbers in JavaScript as a signed 32 bit integer.

Sign up to request clarification or add additional context in comments.

1 Comment

I see. JavaScript is different than other languages that it treats integers as double values, so integer division can be a whole number or a fraction. So there's nothing wrong with the algorithm, just its implementation with JavaScript needs a little tweak. I think using Math.floor() would be fine in this case, performance-wise? Thank you. Marked as accepted.
0

Javascript doesn't have integer division, so you can't just do 5/2 and expect it to give you 2.

If you're looking for an alternative to Math.floor, this website has you covered. It has all of the alternatives you could ever want, and can check which will be the fastest on your browser.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.