Next odd number in javascript

algorithm, javascript, math

Solution

At the question author's request:

The most compact way to achieve it is

b = Math.ceil(a) | 1;

First use `ceil()` to obtain the smallest integer not smaller than `a`, then obtain the smallest odd integer not smaller than `ceil(a)` by doing a bitwise or with 1 to ensure the last bit is set without changing anything else.

To obtain the smallest odd integer strictly larger than `a`, use

b = Math.floor(a+1) | 1;

Caveats:

Bit-operators operate on signed 32-bit integers in Javascript, so the value of `a` must be smaller than or equal to `2^31-1`, resp. strictly smaller for the second. Also, `a` must be larger than `-2^31-1`.

If the representation of signed integers is not two's complement, but ones' complement or sign-and-magnitude (I don't know whether Javascript allows that, Java doesn't, but it's a possibility in C), the value of `a` must be larger than `-1` -- the result of `Math.ceil(a)` resp. `Math.floor(a+1)` must be nonnegative.

Problem

To find the next odd number for an input the following code is being used: ``` a=5.4; // Input b=Math.ceil(a); // Required to turn input to whole number b=b+(((b % 2)-1)*-1); // Gives 7 ``` The ceil rounding function is required. Is this safe and is there a more compact way to do this? EDIT: When the input is already an odd whole number then nothing happens. For example 5.0 will return 5

Original source