Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next odd number in javascript

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

like image 699
zaf Avatar asked Jun 25 '12 17:06

zaf


People also ask

How do you find the next odd number?

The nth odd number is given by the formula 2*n-1.

How do you do odd numbers in JavaScript?

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”.

What is the next odd number after 21?

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.

Which one will give you an odd number in JS?

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.


2 Answers

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.)

like image 191
Pointy Avatar answered Oct 26 '22 00:10

Pointy


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.

like image 24
Daniel Fischer Avatar answered Oct 25 '22 23:10

Daniel Fischer