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
At the question author’s request:
The most compact way to achieve it is
First use
ceil()to obtain the smallest integer not smaller thana, then obtain the smallest odd integer not smaller thanceil(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, useCaveats:
Bit-operators operate on signed 32-bit integers in Javascript, so the value of
amust be smaller than or equal to2^31-1, resp. strictly smaller for the second. Also,amust 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
amust be larger than-1— the result ofMath.ceil(a)resp.Math.floor(a+1)must be nonnegative.