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
The nth odd number is given by the formula 2*n-1.
STEP 1 − Read the number to variable n. STEP 2 − Divide n by 2 and save the remainder in a variable named r. If r==0, print “even” If r!= 0, print “odd”.
The composite odd numbers up to 100 are: 9, 15, 21, 25, 27, 33, 35, 39, 45, 49, 51, 55, 57, 63, 65, 69, 75, 77, 81, 85, 87, 91, 93, 95, 99.
Example 1: Using if...else In the above program, number % 2 == 0 checks whether the number is even. If the remainder is 0, the number is even. In this case, 27 % 2 equals to 1. Hence, the number is odd.
How about just
b += b % 2 ^ 1;
The remainder after dividing by 2 will always be 0 or 1, so the ^
operator (exclusive-OR) flips it to the opposite.
(Also, (b & 1) ^ 1
would work too. Oh, I guess b = b ^ 1
would work for positive integers, but it'd be problematic for big integers.)
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With